Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 3.0 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! What happened during a run, one event per line: printed in full when a
5//! seed is replayed, and cut down to the changesets involved when a check
6//! fails.
7
8use std::collections::BTreeSet;
9
10use braid_format::ObjectId;
11
12/// One event.
13#[derive(Clone, Debug)]
14pub struct Event {
15 /// The scheduler step it happened in.
16 pub step: u64,
17 /// The simulated time.
18 pub time: u64,
19 /// Who acted: an agent, the lander, a check.
20 pub actor: String,
21 /// What happened.
22 pub text: String,
23 /// The changesets it is about.
24 pub ids: Vec<ObjectId>,
25}
26
27impl Event {
28 /// The event as one line.
29 pub fn line(&self) -> String {
30 format!(
31 "step {:>5} t{:<6} {:<9} {}",
32 self.step, self.time, self.actor, self.text
33 )
34 }
35}
36
37/// Every event of a run, in order.
38#[derive(Clone, Debug, Default)]
39pub struct Trace {
40 events: Vec<Event>,
41}
42
43impl Trace {
44 /// Records an event.
45 pub fn push(&mut self, step: u64, time: u64, actor: &str, text: String, ids: &[ObjectId]) {
46 self.events.push(Event {
47 step,
48 time,
49 actor: actor.to_owned(),
50 text,
51 ids: ids.to_vec(),
52 });
53 }
54
55 /// Every event as a line.
56 pub fn lines(&self) -> Vec<String> {
57 self.events.iter().map(Event::line).collect()
58 }
59
60 /// The events about any of `ids`, the first event, and the last `tail`
61 /// events, as lines.
62 pub fn about(&self, ids: &BTreeSet<ObjectId>, tail: usize) -> Vec<String> {
63 let from = self.events.len().saturating_sub(tail);
64 self.events
65 .iter()
66 .enumerate()
67 .filter(|(at, event)| {
68 *at == 0 || *at >= from || event.ids.iter().any(|id| ids.contains(id))
69 })
70 .map(|(_, event)| event.line())
71 .collect()
72 }
73}
74
75/// The first hex digits of an id, enough to tell the changesets of a run
76/// apart.
77pub fn short(id: ObjectId) -> String {
78 id.to_hex()[..10].to_owned()
79}
80
81#[cfg(test)]
82mod tests {
83 use super::*;
84 use braid_format::Kind;
85
86 #[test]
87 fn about_keeps_the_relevant_events() {
88 let a = ObjectId::hash(Kind::Changeset, b"a");
89 let b = ObjectId::hash(Kind::Changeset, b"b");
90 let mut trace = Trace::default();
91 trace.push(0, 0, "setup", "start".to_owned(), &[]);
92 trace.push(1, 1, "agent-1", "about a".to_owned(), &[a]);
93 trace.push(2, 2, "agent-2", "about b".to_owned(), &[b]);
94 trace.push(3, 3, "lander", "about nothing".to_owned(), &[]);
95 trace.push(4, 4, "lander", "last".to_owned(), &[]);
96 let lines = trace.about(&BTreeSet::from([a]), 1);
97 assert_eq!(lines.len(), 3);
98 assert!(lines[0].ends_with("start"));
99 assert!(lines[1].ends_with("about a"));
100 assert!(lines[2].ends_with("last"));
101 assert_eq!(trace.lines().len(), 5);
102 assert_eq!(short(a).len(), 10);
103 }
104}