Skip to main content

artifactize_core/monitor/
model.rs

1//! Pure projections of saved state for the monitor screens.
2mod detail;
3pub use detail::{Card, Detail, Section, card, detail};
4pub(crate) use detail::{entries, raw};
5mod graph;
6pub use graph::{Graph, GraphEdge, GraphNode, Light, graph};
7mod node_id;
8pub use node_id::NodeId;
9mod states;
10mod status;
11#[cfg(test)]
12mod tests;
13pub(crate) mod tree;
14pub use states::{Activity, Busy, Completion, EvalView, NotRun, Queue, Source, Upstream, Waits};
15pub use status::Status;
16pub use tree::{Clock, Kind, Node, Segment, Tally, Tone, Weight, completion, tree, upstream_index};
17
18use time::OffsetDateTime;
19
20use crate::{
21    query,
22    store::{RequestView, RunSummary, RunView},
23    types::{ArtifactName, EvalId},
24};
25
26/// What a tree node shows in the detail pane, parsed from its stable tree identifier.
27#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
28pub enum Target {
29    /// The open Run itself, from the node above its Artifacts.
30    Run,
31    Artifact(crate::types::ArtifactName),
32    Eval(crate::types::EvalId),
33}
34
35impl Target {
36    pub fn parse(id: &str) -> Option<Self> {
37        let (kind, name) = id.split_once(':')?;
38        match kind {
39            "run" => name.parse::<crate::types::RunId>().ok().map(|_| Self::Run),
40            "a" => name.parse().ok().map(Self::Artifact),
41            "e" => name.parse().ok().map(Self::Eval),
42            _ => None,
43        }
44    }
45}
46
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct RunRow {
49    pub id: crate::types::RunId,
50    pub repo: std::path::PathBuf,
51    pub status: crate::types::RunStatus,
52    /// Request status glyphs with their counts, most urgent first, such as `✗1 ✓2`.
53    pub counts: String,
54    pub age: String,
55    /// Wall time of a finished Run.
56    pub took: String,
57    /// What the requester said it is working on, or empty.
58    pub comment: String,
59}
60
61#[derive(Debug, Clone)]
62pub struct Progress {
63    pub status: Status,
64    pub repo: String,
65    /// What the requester said it is working on (`verify --comment`).
66    pub comment: Option<String>,
67    pub validation: String,
68    pub timing: String,
69    /// Elapsed time of a running Run, or how long a finished one took.
70    pub elapsed: String,
71    /// The saved validation snapshot: `None` until the Run ends.
72    pub satisfied: Option<bool>,
73    pub counts: Vec<(Status, u64)>,
74    /// Executions against their budget, and jobs.
75    pub budget: String,
76    /// Executed and reused requests.
77    pub work: String,
78    /// Every spent token counter, and the counters reuse saved.
79    pub usage: String,
80    pub saved: String,
81    /// The spent token total, the only usage the Run headline shows.
82    pub tokens: Option<u64>,
83    /// Eval ID and elapsed time.
84    pub running: Vec<(String, String)>,
85    /// Eval ID and claim state.
86    pub waiting: Vec<(String, String)>,
87    /// Eval ID (or "Run") and message.
88    pub errors: Vec<(String, String)>,
89    /// The evals that need a person's attention, each by its status and ID: RED, then ERROR,
90    /// then the sign-offs and Human reviews that wait.
91    pub needs: Vec<(Status, String)>,
92}
93
94/// The Run headline: one status line, then what needs attention.
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct Strip {
97    pub status: Status,
98    pub headline: String,
99    /// Status and text: errors, then waiting Human reviews, then running evals.
100    pub attention: Vec<(Status, String)>,
101    /// Attention lines beyond the shown ones.
102    pub more: usize,
103}
104
105/// Attention lines shown in the Run headline before `+N more`.
106const ATTENTION_LINES: usize = 3;
107
108const ABSENT: &str = "not in Run";
109
110/// The mark for `status`, or `-` for an eval without one.
111pub fn glyph(status: Option<Status>) -> &'static str {
112    status.map_or("-", Status::glyph)
113}
114
115fn join<T: AsRef<str>>(items: impl IntoIterator<Item = T>, separator: &str) -> String {
116    let items: Vec<_> = items
117        .into_iter()
118        .map(|item| item.as_ref().to_owned())
119        .collect();
120    items.join(separator)
121}
122
123fn mark(name: &EvalId, status: Option<Status>) -> String {
124    format!(
125        "{} {name} {}",
126        glyph(status),
127        status.map_or(ABSENT, Status::as_str)
128    )
129}
130
131/// Seconds per minute, hour and day, the units a duration is shown in.
132const MINUTE: i64 = 60;
133const HOUR: i64 = 60 * MINUTE;
134const DAY: i64 = 24 * HOUR;
135
136pub fn duration(elapsed: time::Duration) -> String {
137    let seconds = elapsed.whole_seconds().max(0);
138    match seconds {
139        0..MINUTE => format!("{seconds}s"),
140        MINUTE..HOUR => format!("{}m {:02}s", seconds / MINUTE, seconds % MINUTE),
141        HOUR..DAY => format!("{}h {:02}m", seconds / HOUR, seconds % HOUR / MINUTE),
142        _ => format!("{}d {}h", seconds / DAY, seconds % DAY / HOUR),
143    }
144}
145
146#[cfg(test)]
147#[test]
148fn typed_durations_keep_the_display_units_and_clamp_clock_skew() {
149    for (elapsed, expected) in [
150        (time::Duration::seconds(-1), "0s"),
151        (time::Duration::ZERO, "0s"),
152        (time::Duration::milliseconds(59_999), "59s"),
153        (time::Duration::minutes(1), "1m 00s"),
154        (time::Duration::seconds(125), "2m 05s"),
155        (time::Duration::hours(1), "1h 00m"),
156        (time::Duration::minutes(61), "1h 01m"),
157        (time::Duration::days(1), "1d 0h"),
158        (time::Duration::hours(25), "1d 1h"),
159    ] {
160        assert_eq!(duration(elapsed), expected);
161    }
162}
163
164/// The tokens a Request's saved attempts spent, `None` for none. The counts are
165/// read from the state, so a sum past `u64::MAX` saturates instead of panicking.
166pub(crate) fn attempt_tokens(attempts: &[crate::llm::Attempt]) -> Option<u64> {
167    let tokens = attempts
168        .iter()
169        .filter_map(|attempt| attempt.usage.get("totalTokens"))
170        .fold(0u64, |total, tokens| total.saturating_add(*tokens));
171    (tokens > 0).then_some(tokens)
172}
173
174#[test]
175fn attempt_tokens_saturate_on_saved_counts() {
176    let attempt = |tokens: u64| -> crate::llm::Attempt {
177        serde_json::from_value(serde_json::json!({ "usage": { "totalTokens": tokens } }))
178            .expect("a saved attempt")
179    };
180    assert_eq!(attempt_tokens(&[]), None);
181    assert_eq!(attempt_tokens(&[attempt(0)]), None);
182    assert_eq!(attempt_tokens(&[attempt(14), attempt(8)]), Some(22));
183    assert_eq!(
184        attempt_tokens(&[attempt(u64::MAX), attempt(1)]),
185        Some(u64::MAX)
186    );
187}
188
189/// Saved RFC 3339 times; an open end is measured to `now`.
190pub(crate) fn span(
191    start: crate::types::Timestamp,
192    end: Option<crate::types::Timestamp>,
193    now: OffsetDateTime,
194) -> Option<String> {
195    let end = end.map_or(now, crate::types::Timestamp::time);
196    Some(duration(end - start.time()))
197}
198
199/// Status counts as glyphs, most urgent first and zero counts left out: `!2 ✓1`.
200pub fn counts(counts: impl IntoIterator<Item = (Status, u64)>) -> String {
201    let mut counts: Vec<_> = counts.into_iter().filter(|(_, n)| *n > 0).collect();
202    counts.sort_by_key(|(status, _)| *status);
203    join(
204        counts
205            .into_iter()
206            .map(|(status, n)| format!("{}{n}", status.glyph())),
207        " ",
208    )
209}
210
211/// Token totals for a headline: `950`, `12.3k`, `3.9M`.
212pub fn tokens(total: u64) -> String {
213    // Headlines abbreviate decimal thousands and millions as k and M, respectively.
214    const THOUSAND: u64 = 1_000;
215    const MILLION: u64 = 1_000_000;
216    match total {
217        0..THOUSAND => total.to_string(),
218        THOUSAND..MILLION => format!("{:.1}k", total as f64 / THOUSAND as f64),
219        _ => format!("{:.1}M", total as f64 / MILLION as f64),
220    }
221}
222
223pub fn run_rows(runs: &[RunSummary], now: OffsetDateTime) -> Vec<RunRow> {
224    runs.iter()
225        .map(|run| RunRow {
226            id: run.id.clone(),
227            repo: run.repo_path.clone(),
228            status: run.status,
229            counts: counts(run.counts.iter().map(|(status, n)| ((*status).into(), *n))),
230            age: span(run.created_at, None, now).unwrap_or_default(),
231            took: run
232                .completed_at
233                .and_then(|end| span(run.created_at, Some(end), now))
234                .unwrap_or_default(),
235            comment: run.comment.as_deref().unwrap_or_default().to_owned(),
236        })
237        .collect()
238}
239
240fn reused(view: &RequestView) -> bool {
241    query::reused(&view.request)
242}
243
244fn elapsed(view: &RequestView, now: OffsetDateTime) -> Option<String> {
245    let request = &view.request;
246    if reused(view) {
247        return Some("reused".into());
248    }
249    let active = matches!(
250        request.status(),
251        crate::types::RequestStatus::Running
252            | crate::types::RequestStatus::WaitingHuman
253            | crate::types::RequestStatus::Deferred
254    );
255    let start = request
256        .started_at
257        .or(active.then_some(request.created_at))?;
258    span(start, request.completed_at(), now)
259}
260
261fn claim(view: &RequestView) -> String {
262    view.claim.as_ref().map_or("unclaimed".into(), |claim| {
263        format!("claimed by {} at {}", claim.reviewer, claim.claimed_at)
264    })
265}
266
267fn error(view: &RequestView) -> Option<String> {
268    let request = &view.request;
269    let error = request.error().map(str::to_owned)?;
270    Some(match &request.error_code() {
271        Some(code) => format!("[{code}] {error}"),
272        None => error,
273    })
274}
275
276pub fn progress(view: &RunView, requests: &[RequestView], now: OffsetDateTime) -> Progress {
277    let run = &view.run;
278    let (summary, saved_usage) = query::run_summary(view, now);
279    let with = |status: crate::types::RequestStatus| {
280        requests
281            .iter()
282            .filter(move |view| view.request.status() == status)
283    };
284    let usage = counter_pairs(&summary.usage.usage);
285    let saved = counter_pairs(&saved_usage);
286    let spent = &summary.usage.usage;
287    let tokens = spent.get("totalTokens").copied().or_else(|| {
288        let input = spent.get("inputTokens").copied();
289        let output = spent.get("outputTokens").copied();
290        (input.is_some() || output.is_some())
291            .then(|| input.unwrap_or(0).saturating_add(output.unwrap_or(0)))
292    });
293    let validation = run.validation.snapshot();
294    let unmet = validation
295        .and_then(|v| v.obligations.value())
296        .map(|ids| {
297            ids.iter()
298                .map(ToString::to_string)
299                .collect::<Vec<_>>()
300                .join(", ")
301        })
302        .unwrap_or_default();
303    let wall = span(run.created_at, run.completed_at(), now).unwrap_or_default();
304    Progress {
305        status: run.status().into(),
306        repo: crate::platform::path_text(&run.repo_path),
307        comment: run.comment.as_ref().map(ToString::to_string),
308        // The saved snapshot; the tree shows the current state.
309        validation: match validation.and_then(|v| v.satisfied.value()) {
310            None => "pending".into(),
311            Some(true) => "SATISFIED at Run end".into(),
312            Some(_) if unmet.is_empty() => "NOT SATISFIED at Run end".into(),
313            Some(_) => format!("NOT SATISFIED at Run end (unmet: {unmet})"),
314        },
315        timing: format!(
316            "started {} · {} {wall}",
317            run.created_at,
318            if run.completed_at().is_some() {
319                "took"
320            } else {
321                "elapsed"
322            },
323        ),
324        elapsed: wall,
325        satisfied: validation.and_then(|v| v.satisfied.value()).copied(),
326        counts: summary
327            .counts
328            .iter()
329            .map(|(status, count)| ((*status).into(), *count))
330            .collect(),
331        budget: format!(
332            "executions {}/{} · jobs {}",
333            run.executions_started,
334            run.max_executions
335                .map_or("unlimited".into(), |max| max.to_string()),
336            run.jobs
337                .map_or("unlimited".into(), |limit| limit.to_string()),
338        ),
339        work: format!(
340            "executed {} · reused {}",
341            summary.executed.total, summary.reused.kinds.total,
342        ),
343        usage,
344        saved,
345        tokens,
346        running: with(crate::types::RequestStatus::Running)
347            .map(|view| {
348                (
349                    view.request.eval_id.to_string(),
350                    elapsed(view, now).unwrap_or_default(),
351                )
352            })
353            .collect(),
354        waiting: requests
355            .iter()
356            .filter(|view| view.request.status().is_human_wait())
357            .map(|view| (view.request.eval_id.to_string(), claim(view)))
358            .collect(),
359        errors: with(crate::types::RequestStatus::Error)
360            .map(|view| {
361                (
362                    view.request.eval_id.to_string(),
363                    error(view).unwrap_or_default(),
364                )
365            })
366            .chain(
367                run.error()
368                    .map(str::to_owned)
369                    .map(|error| ("Run".into(), error)),
370            )
371            .chain(
372                view.unreadable
373                    .iter()
374                    .map(|record| (record.id.clone(), record.to_string())),
375            )
376            .collect(),
377        needs: with(crate::types::RequestStatus::Red)
378            .chain(with(crate::types::RequestStatus::Error))
379            .chain(
380                requests
381                    .iter()
382                    .filter(|view| view.request.status().is_human_wait()),
383            )
384            .map(|view| {
385                (
386                    Status::from(view.request.status()),
387                    view.request.eval_id.to_string(),
388                )
389            })
390            .collect(),
391    }
392}
393
394impl Progress {
395    pub fn finished(&self) -> bool {
396        !matches!(self.status, Status::Running | Status::WaitingHuman)
397    }
398}
399
400/// The Run headline from its progress: snapshot verdict, counts, time and token total.
401pub fn strip(progress: &Progress) -> Strip {
402    let validation = match progress.satisfied {
403        None => "validation pending".to_owned(),
404        Some(true) => "SATISFIED at Run end".to_owned(),
405        Some(false) => "NOT SATISFIED at Run end".to_owned(),
406    };
407    let counts = counts(progress.counts.iter().copied());
408    let time = format!(
409        "{} {}",
410        if progress.finished() {
411            "took"
412        } else {
413            "elapsed"
414        },
415        progress.elapsed
416    );
417    let tokens = progress
418        .tokens
419        .map(|total| format!("tokens {}", tokens(total)));
420    let headline = join(
421        [Some(validation), Some(counts), Some(time), tokens]
422            .into_iter()
423            .flatten()
424            .filter(|part| !part.is_empty()),
425        " · ",
426    );
427    let mut attention: Vec<(Status, String)> = progress
428        .errors
429        .iter()
430        .map(|(eval, error)| (Status::Error, format!("{eval}  {error}")))
431        .chain(progress.waiting.iter().map(|(eval, claim)| {
432            (
433                Status::WaitingHuman,
434                format!("{eval}  waiting Human · {claim}"),
435            )
436        }))
437        .chain(progress.running.iter().map(|(eval, time)| {
438            (
439                Status::Running,
440                format!("{eval}  running {time}").trim_end().to_owned(),
441            )
442        }))
443        .collect();
444    let more = attention.len().saturating_sub(ATTENTION_LINES);
445    attention.truncate(ATTENTION_LINES);
446    Strip {
447        status: progress.status,
448        headline,
449        attention,
450        more,
451    }
452}
453
454/// The row above the Artifacts; Enter on it opens the Run detail.
455pub fn run_node(run: &RunView) -> Node {
456    let status = Status::from(run.run.status());
457    Node {
458        id: NodeId::run(&run.run.id),
459        clock: None,
460        kind: Kind::Artifact {
461            completion: Completion::Complete,
462            basis: false,
463        },
464        glyph: status.glyph(),
465        tone: match status {
466            Status::Green => Tone::Green,
467            Status::Red => Tone::Red,
468            Status::Error => Tone::Error,
469            Status::Running => Tone::Running,
470            Status::Blocked | Status::BudgetExhausted | Status::Incomplete => Tone::Blocked,
471            _ => Tone::Muted,
472        },
473        weight: Weight::Normal,
474        name: "Run".into(),
475        marks: String::new(),
476        text: vec![Segment {
477            text: "Enter: usage, budgets, counts".into(),
478            tone: Some(Tone::Muted),
479        }],
480        right: String::new(),
481        compact: String::new(),
482        tally: None,
483        changed: false,
484        upstream: Vec::new(),
485        held: false,
486        parts: Vec::new(),
487        children: Vec::new(),
488    }
489}
490
491/// Saved Run definitions joined with the Run's requests.
492struct Saved<'a> {
493    run: &'a RunView,
494    requests: &'a [RequestView],
495}
496
497impl<'a> Saved<'a> {
498    fn definitions(&self) -> Option<&'a crate::store::definitions::Graph> {
499        self.run.run.definitions.graph()
500    }
501    fn artifacts(
502        &self,
503    ) -> impl Iterator<
504        Item = (
505            &'a crate::types::ArtifactName,
506            &'a crate::store::definitions::Artifact,
507        ),
508    > {
509        self.definitions()
510            .into_iter()
511            .flat_map(|graph| graph.artifacts())
512    }
513    fn artifact(&self, id: &ArtifactName) -> Option<&'a crate::store::definitions::Artifact> {
514        self.definitions().and_then(|graph| graph.artifact(id))
515    }
516    fn eval_definitions(&self) -> &'a [crate::store::definitions::Eval] {
517        self.definitions().map_or(&[], |graph| graph.evals())
518    }
519    fn components(&self) -> &'a [crate::store::definitions::Component] {
520        self.definitions().map_or(&[], |graph| graph.components())
521    }
522
523    fn request(&self, eval: &EvalId) -> Option<&'a RequestView> {
524        self.requests
525            .iter()
526            .find(|view| &view.request.eval_id == eval)
527    }
528
529    fn status(&self, eval: &EvalId) -> Option<Status> {
530        self.request(eval).map(|view| view.request.status().into())
531    }
532
533    /// Dependency-first component order with cycle peers by name, then any other saved or
534    /// requested Artifact.
535    fn artifact_ids(&self) -> Vec<&'a ArtifactName> {
536        let components = self.components().iter();
537        let saved = components
538            .flat_map(|component| {
539                let mut members: Vec<_> =
540                    component.artifacts.value().into_iter().flatten().collect();
541                members.sort_unstable();
542                members
543            })
544            .chain(self.artifacts().map(|(id, _)| id))
545            .chain(self.requests.iter().map(|view| &view.request.target));
546        let mut seen = std::collections::HashSet::new();
547        saved.filter(|id| seen.insert(*id)).collect()
548    }
549
550    /// Saved Eval definitions targeting the Artifact, then requests without one.
551    fn evals(
552        &self,
553        artifact: &ArtifactName,
554    ) -> Vec<(&'a EvalId, Option<&'a crate::store::definitions::Eval>)> {
555        let mut evals: Vec<_> = self
556            .eval_definitions()
557            .iter()
558            .filter(|eval| &eval.target == artifact)
559            .map(|eval| (&eval.id, Some(eval)))
560            .collect();
561        for request in self.requests.iter().map(|view| &view.request) {
562            if &request.target == artifact && !evals.iter().any(|(id, _)| *id == &request.eval_id) {
563                evals.push((&request.eval_id, None));
564            }
565        }
566        evals
567    }
568
569    fn validation(&self, artifact: &ArtifactName) -> Option<&'a crate::store::ArtifactValidation> {
570        self.run
571            .run
572            .validation
573            .snapshot()?
574            .artifacts
575            .value()?
576            .iter()
577            .find(|a| &a.id == artifact)
578    }
579
580    fn component(&self, id: &ArtifactName) -> Option<&'a crate::store::definitions::Component> {
581        self.components().iter().find(|component| {
582            component
583                .artifacts
584                .value()
585                .is_some_and(|artifacts| artifacts.iter().any(|artifact| artifact == id))
586        })
587    }
588
589    /// Each Artifact with its direct parts.
590    fn parts(&self) -> std::collections::BTreeMap<&'a ArtifactName, Vec<&'a ArtifactName>> {
591        let mut parts: std::collections::BTreeMap<_, Vec<_>> = Default::default();
592        for relation in self
593            .definitions()
594            .into_iter()
595            .flat_map(|graph| graph.relations())
596        {
597            if matches!(relation.kind, crate::store::definitions::RelationKind::Part) {
598                parts
599                    .entry(&relation.target)
600                    .or_default()
601                    .push(&relation.source);
602            }
603        }
604        parts
605    }
606
607    fn relations(
608        &self,
609        artifact: &ArtifactName,
610        input: bool,
611    ) -> Vec<&'a crate::store::definitions::Relation> {
612        self.definitions()
613            .into_iter()
614            .flat_map(|graph| graph.relations())
615            .filter(|relation| {
616                if input {
617                    &relation.target == artifact
618                } else {
619                    &relation.source == artifact
620                }
621            })
622            .collect()
623    }
624}
625
626fn relation_kind(relation: &crate::store::definitions::Relation) -> String {
627    use crate::store::definitions::RelationKind;
628    let kind = match &relation.kind {
629        RelationKind::Unknown { .. } => serde_json::to_string(relation).unwrap_or_default(),
630        RelationKind::Part => "part".into(),
631        RelationKind::Child { path } => format!(
632            "child {}",
633            path.value().map_or("", crate::config::ChildPrefix::as_str)
634        ),
635        RelationKind::Instruction { name, eval_id } => format!("{{{name}}} in {eval_id}"),
636        RelationKind::Argument {
637            eval_id,
638            index,
639            name,
640            ..
641        } => format!("argv {eval_id}[{index}] {{{name}}}"),
642    };
643    if relation.cyclic.value() == Some(&true) {
644        format!("{kind} ↻")
645    } else {
646        kind
647    }
648}
649
650fn counter_pairs(counters: &std::collections::BTreeMap<String, u64>) -> String {
651    join(
652        counters
653            .iter()
654            .map(|(name, value)| format!("{name} {value}")),
655        ", ",
656    )
657}
658
659#[cfg(any(test, feature = "test-support"))]
660pub fn derivation_count(run: &RunView, requests: &[RequestView]) -> usize {
661    states::States::new(&Saved { run, requests })
662        .derivations
663        .get()
664}