Skip to main content

artifactize_core/monitor/
model.rs

1//! Pure projections of saved state for the monitor screens.
2mod detail;
3pub(crate) use detail::raw;
4pub use detail::{Card, Detail, Section, card, detail};
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/// The tokens a Request's saved attempts spent, `None` for none. The counts are
147/// read from the state, so a sum past `u64::MAX` saturates instead of panicking.
148pub(crate) fn attempt_tokens(attempts: &[crate::llm::Attempt]) -> Option<u64> {
149    let tokens = attempts
150        .iter()
151        .filter_map(|attempt| attempt.usage.get("totalTokens"))
152        .fold(0u64, |total, tokens| total.saturating_add(*tokens));
153    (tokens > 0).then_some(tokens)
154}
155
156/// Saved RFC 3339 times; an open end is measured to `now`.
157pub(crate) fn span(
158    start: crate::types::Timestamp,
159    end: Option<crate::types::Timestamp>,
160    now: OffsetDateTime,
161) -> Option<String> {
162    let end = end.map_or(now, crate::types::Timestamp::time);
163    Some(duration(end - start.time()))
164}
165
166/// Status counts as glyphs, most urgent first and zero counts left out: `!2 ✓1`.
167pub fn counts(counts: impl IntoIterator<Item = (Status, u64)>) -> String {
168    let mut counts: Vec<_> = counts.into_iter().filter(|(_, n)| *n > 0).collect();
169    counts.sort_by_key(|(status, _)| *status);
170    join(
171        counts
172            .into_iter()
173            .map(|(status, n)| format!("{}{n}", status.glyph())),
174        " ",
175    )
176}
177
178/// Token totals for a headline: `950`, `12.3k`, `3.9M`.
179pub fn tokens(total: u64) -> String {
180    // Headlines abbreviate decimal thousands and millions as k and M, respectively.
181    const THOUSAND: u64 = 1_000;
182    const MILLION: u64 = 1_000_000;
183    match total {
184        0..THOUSAND => total.to_string(),
185        THOUSAND..MILLION => format!("{:.1}k", total as f64 / THOUSAND as f64),
186        _ => format!("{:.1}M", total as f64 / MILLION as f64),
187    }
188}
189
190pub fn run_rows(runs: &[RunSummary], now: OffsetDateTime) -> Vec<RunRow> {
191    runs.iter()
192        .map(|run| RunRow {
193            id: run.id.clone(),
194            repo: run.repo_path.clone(),
195            status: run.status,
196            counts: counts(run.counts.iter().map(|(status, n)| ((*status).into(), *n))),
197            age: span(run.created_at, None, now).unwrap_or_default(),
198            took: run
199                .completed_at
200                .and_then(|end| span(run.created_at, Some(end), now))
201                .unwrap_or_default(),
202            comment: run.comment.as_deref().unwrap_or_default().to_owned(),
203        })
204        .collect()
205}
206
207fn reused(view: &RequestView) -> bool {
208    query::reused(&view.request)
209}
210
211fn elapsed(view: &RequestView, now: OffsetDateTime) -> Option<String> {
212    let request = &view.request;
213    if reused(view) {
214        return Some("reused".into());
215    }
216    let active = matches!(
217        request.status(),
218        crate::types::RequestStatus::Running
219            | crate::types::RequestStatus::WaitingHuman
220            | crate::types::RequestStatus::Deferred
221    );
222    let start = request
223        .started_at
224        .or(active.then_some(request.created_at))?;
225    span(start, request.completed_at(), now)
226}
227
228fn claim(view: &RequestView) -> String {
229    view.claim.as_ref().map_or("unclaimed".into(), |claim| {
230        format!("claimed by {} at {}", claim.reviewer, claim.claimed_at)
231    })
232}
233
234fn error(view: &RequestView) -> Option<String> {
235    let request = &view.request;
236    let error = request.error().map(str::to_owned)?;
237    Some(match &request.error_code() {
238        Some(code) => format!("[{code}] {error}"),
239        None => error,
240    })
241}
242
243pub fn progress(view: &RunView, requests: &[RequestView], now: OffsetDateTime) -> Progress {
244    let run = &view.run;
245    let (summary, saved_usage) = query::run_summary(view, now);
246    let with = |status: crate::types::RequestStatus| {
247        requests
248            .iter()
249            .filter(move |view| view.request.status() == status)
250    };
251    let usage = counter_pairs(&summary.usage.usage);
252    let saved = counter_pairs(&saved_usage);
253    let spent = &summary.usage.usage;
254    let tokens = spent.get("totalTokens").copied().or_else(|| {
255        let input = spent.get("inputTokens").copied();
256        let output = spent.get("outputTokens").copied();
257        (input.is_some() || output.is_some())
258            .then(|| input.unwrap_or(0).saturating_add(output.unwrap_or(0)))
259    });
260    let validation = run.validation.snapshot();
261    let unmet = validation
262        .and_then(|v| v.obligations.value())
263        .map(|ids| {
264            ids.iter()
265                .map(ToString::to_string)
266                .collect::<Vec<_>>()
267                .join(", ")
268        })
269        .unwrap_or_default();
270    let wall = span(run.created_at, run.completed_at(), now).unwrap_or_default();
271    Progress {
272        status: run.status().into(),
273        repo: crate::platform::path_text(&run.repo_path),
274        comment: run.comment.as_ref().map(ToString::to_string),
275        // The saved snapshot; the tree shows the current state.
276        validation: match validation.and_then(|v| v.satisfied.value()) {
277            None => "pending".into(),
278            Some(true) => "SATISFIED at Run end".into(),
279            Some(_) if unmet.is_empty() => "NOT SATISFIED at Run end".into(),
280            Some(_) => format!("NOT SATISFIED at Run end (unmet: {unmet})"),
281        },
282        timing: format!(
283            "started {} · {} {wall}",
284            run.created_at,
285            if run.completed_at().is_some() {
286                "took"
287            } else {
288                "elapsed"
289            },
290        ),
291        elapsed: wall,
292        satisfied: validation.and_then(|v| v.satisfied.value()).copied(),
293        counts: summary
294            .counts
295            .iter()
296            .map(|(status, count)| ((*status).into(), *count))
297            .collect(),
298        budget: format!(
299            "executions {}/{} · jobs {}",
300            run.executions_started,
301            run.max_executions
302                .map_or("unlimited".into(), |max| max.to_string()),
303            run.jobs
304                .map_or("unlimited".into(), |limit| limit.to_string()),
305        ),
306        work: format!(
307            "executed {} · reused {}",
308            summary.executed.total, summary.reused.kinds.total,
309        ),
310        usage,
311        saved,
312        tokens,
313        running: with(crate::types::RequestStatus::Running)
314            .map(|view| {
315                (
316                    view.request.eval_id.to_string(),
317                    elapsed(view, now).unwrap_or_default(),
318                )
319            })
320            .collect(),
321        waiting: requests
322            .iter()
323            .filter(|view| view.request.status().is_human_wait())
324            .map(|view| (view.request.eval_id.to_string(), claim(view)))
325            .collect(),
326        errors: with(crate::types::RequestStatus::Error)
327            .map(|view| {
328                (
329                    view.request.eval_id.to_string(),
330                    error(view).unwrap_or_default(),
331                )
332            })
333            .chain(
334                run.error()
335                    .map(str::to_owned)
336                    .map(|error| ("Run".into(), error)),
337            )
338            .chain(
339                view.unreadable
340                    .iter()
341                    .map(|record| (record.id.clone(), record.to_string())),
342            )
343            .collect(),
344        needs: with(crate::types::RequestStatus::Red)
345            .chain(with(crate::types::RequestStatus::Error))
346            .chain(
347                requests
348                    .iter()
349                    .filter(|view| view.request.status().is_human_wait()),
350            )
351            .map(|view| {
352                (
353                    Status::from(view.request.status()),
354                    view.request.eval_id.to_string(),
355                )
356            })
357            .collect(),
358    }
359}
360
361impl Progress {
362    pub fn finished(&self) -> bool {
363        !matches!(self.status, Status::Running | Status::WaitingHuman)
364    }
365}
366
367/// The Run headline from its progress: snapshot verdict, counts, time and token total.
368pub fn strip(progress: &Progress) -> Strip {
369    let validation = match progress.satisfied {
370        None => "validation pending".to_owned(),
371        Some(true) => "SATISFIED at Run end".to_owned(),
372        Some(false) => "NOT SATISFIED at Run end".to_owned(),
373    };
374    let counts = counts(progress.counts.iter().copied());
375    let time = format!(
376        "{} {}",
377        if progress.finished() {
378            "took"
379        } else {
380            "elapsed"
381        },
382        progress.elapsed
383    );
384    let tokens = progress
385        .tokens
386        .map(|total| format!("tokens {}", tokens(total)));
387    let headline = join(
388        [Some(validation), Some(counts), Some(time), tokens]
389            .into_iter()
390            .flatten()
391            .filter(|part| !part.is_empty()),
392        " · ",
393    );
394    let mut attention: Vec<(Status, String)> = progress
395        .errors
396        .iter()
397        .map(|(eval, error)| (Status::Error, format!("{eval}  {error}")))
398        .chain(progress.waiting.iter().map(|(eval, claim)| {
399            (
400                Status::WaitingHuman,
401                format!("{eval}  waiting Human · {claim}"),
402            )
403        }))
404        .chain(progress.running.iter().map(|(eval, time)| {
405            (
406                Status::Running,
407                format!("{eval}  running {time}").trim_end().to_owned(),
408            )
409        }))
410        .collect();
411    let more = attention.len().saturating_sub(ATTENTION_LINES);
412    attention.truncate(ATTENTION_LINES);
413    Strip {
414        status: progress.status,
415        headline,
416        attention,
417        more,
418    }
419}
420
421/// The row above the Artifacts; Enter on it opens the Run detail.
422pub fn run_node(run: &RunView) -> Node {
423    let status = Status::from(run.run.status());
424    Node {
425        id: NodeId::run(&run.run.id),
426        clock: None,
427        kind: Kind::Artifact {
428            completion: Completion::Complete,
429            basis: false,
430        },
431        glyph: status.glyph(),
432        tone: match status {
433            Status::Green => Tone::Green,
434            Status::Red => Tone::Red,
435            Status::Error => Tone::Error,
436            Status::Running => Tone::Running,
437            Status::Blocked | Status::BudgetExhausted | Status::Incomplete => Tone::Blocked,
438            _ => Tone::Muted,
439        },
440        weight: Weight::Normal,
441        name: "Run".into(),
442        marks: String::new(),
443        text: vec![Segment {
444            text: "Enter: usage, budgets, counts".into(),
445            tone: Some(Tone::Muted),
446        }],
447        right: String::new(),
448        compact: String::new(),
449        tally: None,
450        changed: false,
451        upstream: Vec::new(),
452        held: false,
453        parts: Vec::new(),
454        children: Vec::new(),
455    }
456}
457
458/// Saved Run definitions joined with the Run's requests.
459struct Saved<'a> {
460    run: &'a RunView,
461    requests: &'a [RequestView],
462}
463
464impl<'a> Saved<'a> {
465    fn definitions(&self) -> Option<&'a crate::store::definitions::Graph> {
466        self.run.run.definitions.graph()
467    }
468    fn artifacts(
469        &self,
470    ) -> impl Iterator<
471        Item = (
472            &'a crate::types::ArtifactName,
473            &'a crate::store::definitions::Artifact,
474        ),
475    > {
476        self.definitions()
477            .into_iter()
478            .flat_map(|graph| graph.artifacts())
479    }
480    fn artifact(&self, id: &ArtifactName) -> Option<&'a crate::store::definitions::Artifact> {
481        self.definitions().and_then(|graph| graph.artifact(id))
482    }
483    fn eval_definitions(&self) -> &'a [crate::store::definitions::Eval] {
484        self.definitions().map_or(&[], |graph| graph.evals())
485    }
486    fn components(&self) -> &'a [crate::store::definitions::Component] {
487        self.definitions().map_or(&[], |graph| graph.components())
488    }
489
490    fn request(&self, eval: &EvalId) -> Option<&'a RequestView> {
491        self.requests
492            .iter()
493            .find(|view| &view.request.eval_id == eval)
494    }
495
496    fn status(&self, eval: &EvalId) -> Option<Status> {
497        self.request(eval).map(|view| view.request.status().into())
498    }
499
500    /// Dependency-first component order with cycle peers by name, then any other saved or
501    /// requested Artifact.
502    fn artifact_ids(&self) -> Vec<&'a ArtifactName> {
503        let components = self.components().iter();
504        let saved = components
505            .flat_map(|component| {
506                let mut members: Vec<_> =
507                    component.artifacts.value().into_iter().flatten().collect();
508                members.sort_unstable();
509                members
510            })
511            .chain(self.artifacts().map(|(id, _)| id))
512            .chain(self.requests.iter().map(|view| &view.request.target));
513        let mut seen = std::collections::HashSet::new();
514        saved.filter(|id| seen.insert(*id)).collect()
515    }
516
517    /// Saved Eval definitions targeting the Artifact, then requests without one.
518    fn evals(
519        &self,
520        artifact: &ArtifactName,
521    ) -> Vec<(&'a EvalId, Option<&'a crate::store::definitions::Eval>)> {
522        let mut evals: Vec<_> = self
523            .eval_definitions()
524            .iter()
525            .filter(|eval| &eval.target == artifact)
526            .map(|eval| (&eval.id, Some(eval)))
527            .collect();
528        for request in self.requests.iter().map(|view| &view.request) {
529            if &request.target == artifact && !evals.iter().any(|(id, _)| *id == &request.eval_id) {
530                evals.push((&request.eval_id, None));
531            }
532        }
533        evals
534    }
535
536    fn validation(&self, artifact: &ArtifactName) -> Option<&'a crate::store::ArtifactValidation> {
537        self.run
538            .run
539            .validation
540            .snapshot()?
541            .artifacts
542            .value()?
543            .iter()
544            .find(|a| &a.id == artifact)
545    }
546
547    fn component(&self, id: &ArtifactName) -> Option<&'a crate::store::definitions::Component> {
548        self.components().iter().find(|component| {
549            component
550                .artifacts
551                .value()
552                .is_some_and(|artifacts| artifacts.iter().any(|artifact| artifact == id))
553        })
554    }
555
556    /// Each Artifact with its direct parts.
557    fn parts(&self) -> std::collections::BTreeMap<&'a ArtifactName, Vec<&'a ArtifactName>> {
558        let mut parts: std::collections::BTreeMap<_, Vec<_>> = Default::default();
559        for relation in self
560            .definitions()
561            .into_iter()
562            .flat_map(|graph| graph.relations())
563        {
564            if matches!(relation.kind, crate::store::definitions::RelationKind::Part) {
565                parts
566                    .entry(&relation.target)
567                    .or_default()
568                    .push(&relation.source);
569            }
570        }
571        parts
572    }
573
574    fn relations(
575        &self,
576        artifact: &ArtifactName,
577        input: bool,
578    ) -> Vec<&'a crate::store::definitions::Relation> {
579        self.definitions()
580            .into_iter()
581            .flat_map(|graph| graph.relations())
582            .filter(|relation| {
583                if input {
584                    &relation.target == artifact
585                } else {
586                    &relation.source == artifact
587                }
588            })
589            .collect()
590    }
591}
592
593fn relation_kind(relation: &crate::store::definitions::Relation) -> String {
594    use crate::store::definitions::RelationKind;
595    let kind = match &relation.kind {
596        RelationKind::Unknown { .. } => serde_json::to_string(relation).unwrap_or_default(),
597        RelationKind::Part => "part".into(),
598        RelationKind::Child { path } => format!(
599            "child {}",
600            path.value().map_or("", crate::config::ChildPrefix::as_str)
601        ),
602        RelationKind::Instruction { name, eval_id } => format!("{{{name}}} in {eval_id}"),
603        RelationKind::Argument {
604            eval_id,
605            index,
606            name,
607            ..
608        } => format!("argv {eval_id}[{index}] {{{name}}}"),
609    };
610    if relation.cyclic.value() == Some(&true) {
611        format!("{kind} ↻")
612    } else {
613        kind
614    }
615}
616
617fn counter_pairs(counters: &std::collections::BTreeMap<String, u64>) -> String {
618    join(
619        counters
620            .iter()
621            .map(|(name, value)| format!("{name} {value}")),
622        ", ",
623    )
624}
625
626#[cfg(any(test, feature = "test-support"))]
627#[path = "model/tests/support.rs"]
628mod support;
629#[cfg(any(test, feature = "test-support"))]
630pub use support::derivation_count;