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