repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

test(golden): checked-in session corpus with byte-identical replay traces

4980d065480b823eddb0b0d3005673208258373b

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (8)

+454 / −0 text lines · 3 binary (striped old/new sizes in 64-byte units, not churn) · lines and sizes scale separately

Diff layout

smith-core/tests/golden.rs

Added
new file mode 100644

+327 / −0 text lines

1//! Golden session corpus (`SMH-SPEC-SPEC0001`, Sessions; Replay and VCS).
2//!
3//! `tests/golden/` holds session files written through the real store
4//! (`create_session`, then `SessionWriter::append_frame`) with fixed ids and
5//! timestamps, and each one's `build_trace` as pretty JSON:
6//!
7//! - `linear_chat`: three user and assistant turns,
8//! - `tool_compaction`: a tool call, its result, and a compaction boundary,
9//! - `sibling_branches`: two answers to one root, the second one continued.
10//!
11//! For every `<name>.smh` the test asserts that
12//!
13//! - loading reports no damage and re-encoding every frame reproduces the file
14//! byte for byte,
15//! - `build_trace` of the loaded session equals `<name>.trace.json` byte for
16//! byte,
17//! - forking at the selected leaf keeps every record and decodes to the same
18//! content,
19//! - the session has the shape its name promises,
20//! - writing the corpus again from code produces the same bytes, so writer
21//! determinism is pinned too.
22//!
23//! Regeneration is a deliberate, versioned act and has one command:
24//!
25//! ```text
26//! SMITH_GOLDEN=regenerate cargo test -p smith-core --test golden
27//! ```
28//!
29//! It refuses unless `frame::VERSION_ENTRY` differs from the number recorded
30//! in `golden/VERSION` (or that file is missing), then rewrites every file
31//! and `VERSION`. Without regeneration, a `VERSION` that differs from
32//! `frame::VERSION_ENTRY` fails the test: an entry frame version bump must
33//! come with a regenerated corpus.
35use smith::config::Config;
36use smith::id::{BranchId, EntryId, MessageId, SessionId, ToolCallId};
37use smith::message::{ContentBlock, Message, Role};
38use smith_core::frame::{Frame, VERSION_ENTRY};
39use smith_core::session::{COMPACTION_KIND, EntryContent, EntryFrame, Session, SessionHeader};
40use smith_core::store::{create_session, load_session};
41use smith_core::trace::build_trace;
42use std::path::{Path, PathBuf};
44/// Timestamp of the first entry of every corpus; entries tick by one second.
45const EPOCH_MS: i64 = 1_767_225_600_000;
47/// Environment switch and the one value that regenerates the corpus.
48const SWITCH: &str = "SMITH_GOLDEN";
49const REGENERATE: &str = "regenerate";
51fn golden_dir() -> PathBuf {
52 Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden")
53}
55/// One corpus session: fixed identity and entry frames in file order.
56struct Corpus {
57 name: &'static str,
58 /// Distinguishes the ids of one corpus from every other one.
59 tag: u128,
60 header: SessionHeader,
61 entries: Vec<EntryFrame>,
62 /// Asserts the loaded session has the shape the name promises.
63 shape: fn(&Session),
64}
66impl Corpus {
67 fn new(name: &'static str, tag: u128, shape: fn(&Session)) -> Self {
68 Self {
69 name,
70 tag,
71 header: SessionHeader {
72 session_id: SessionId::from_u128(tag << 64 | 0x5E55),
73 branch_id: BranchId::from_u128(tag << 64 | 0xB4A0),
74 },
75 entries: Vec::new(),
76 shape,
77 }
78 }
80 /// The id with serial `n` in namespace `kind` of this corpus.
81 const fn bits(&self, kind: u128, n: usize) -> u128 {
82 self.tag << 64 | kind << 32 | n as u128
83 }
85 fn last(&self) -> Option<EntryId> {
86 self.entries.last().map(|entry| entry.id)
87 }
89 fn next_ms(&self) -> i64 {
90 EPOCH_MS + 1_000 * i64::try_from(self.entries.len()).unwrap()
91 }
93 /// Append `content` under `parent` with the next fixed id and timestamp.
94 fn push_at(&mut self, parent: Option<EntryId>, content: &EntryContent) -> EntryId {
95 let id = EntryId::from_u128(self.bits(1, self.entries.len() + 1));
96 self.entries.push(EntryFrame {
97 id,
98 timestamp_ms: self.next_ms(),
99 ..EntryFrame::new(parent, content).unwrap()
100 });
101 id
102 }
104 /// Append `content` under the last entry.
105 fn push(&mut self, content: &EntryContent) -> EntryId {
106 self.push_at(self.last(), content)
107 }
109 /// A message with the next fixed message id, stamped like its entry.
110 fn message(&self, role: Role, blocks: Vec<ContentBlock>) -> EntryContent {
111 EntryContent::Message(Message {
112 id: MessageId::from_u128(self.bits(2, self.entries.len() + 1)),
113 role,
114 blocks,
115 timestamp_ms: self.next_ms(),
116 })
117 }
119 fn say(&mut self, role: Role, text: &str) -> EntryId {
120 let content = self.message(role, vec![ContentBlock::text(text)]);
121 self.push(&content)
122 }
124 /// Write the corpus through the store into a scratch directory and
125 /// return the file bytes: the first entry is published by
126 /// `create_session`, every later one appended by its writer.
127 fn write(&self) -> Vec<u8> {
128 let dir =
129 std::env::temp_dir().join(format!("smith_golden_{}_{}", std::process::id(), self.name));
130 let _ = std::fs::remove_dir_all(&dir);
131 std::fs::create_dir_all(&dir).unwrap();
132 let path = dir.join(format!("{}.smh", self.name));
133 let frames = |entries: &[EntryFrame]| {
134 std::iter::once(Frame::Header {
135 header: self.header,
136 })
137 .chain(entries.iter().cloned().map(|entry| Frame::Known { entry }))
138 .collect::<Vec<_>>()
139 };
140 let (created, appended) = self.entries.split_at(1);
141 {
142 let seed = Session::from_frames(&frames(created)).unwrap();
143 let mut opened = create_session(&path, &seed, Config::default_valid()).unwrap();
144 for entry in appended {
145 opened
146 .writer
147 .append_frame(&Frame::Known {
148 entry: entry.clone(),
149 })
150 .unwrap();
151 }
152 }
153 let bytes = std::fs::read(&path).unwrap();
154 std::fs::remove_dir_all(&dir).unwrap();
155 bytes
156 }
157}
159fn linear_chat() -> Corpus {
160 let mut corpus = Corpus::new("linear_chat", 0xA, |session| {
161 assert_eq!(session.branches().len(), 1);
162 assert_eq!(session.active_branch().entries().len(), 6);
163 });
164 for (question, answer) in [
165 ("hello", "hi, what are we building?"),
166 ("list the files", "a.txt and b.txt"),
167 ("thanks", "you are welcome"),
168 ] {
169 corpus.say(Role::User, question);
170 corpus.say(Role::Assistant, answer);
171 }
172 corpus
173}
175fn tool_compaction() -> Corpus {
176 let mut corpus = Corpus::new("tool_compaction", 0xB, |session| {
177 let boundary = session.compaction_boundary().unwrap();
178 let entries = session.active_branch().entries();
179 assert!(
180 entries
181 .iter()
182 .any(|entry| entry.id == boundary && entry.is_compaction())
183 );
184 });
185 let call_id = ToolCallId::from_u128(corpus.bits(3, 1));
186 let input = serde_json::json!({"path": "notes.txt"});
187 corpus.say(Role::User, "read notes.txt");
188 let request = corpus.message(
189 Role::Assistant,
190 vec![ContentBlock::tool_use("read", input.clone(), call_id)],
191 );
192 corpus.push(&request);
193 corpus.push(&EntryContent::ToolCall {
194 name: "read".to_string(),
195 input,
196 call_id,
197 });
198 corpus.push(&EntryContent::ToolResult {
199 ok: true,
200 output: "buy milk".to_string(),
201 call_id,
202 });
203 corpus.say(Role::Assistant, "notes.txt says: buy milk");
204 corpus.push(&EntryContent::Meta {
205 kind: COMPACTION_KIND.to_string(),
206 detail: serde_json::json!({"summary": "user read notes.txt", "entries": 5}),
207 });
208 corpus.say(Role::User, "and after compaction?");
209 corpus.say(Role::Assistant, "still: buy milk");
210 corpus
211}
213fn sibling_branches() -> Corpus {
214 let mut corpus = Corpus::new("sibling_branches", 0xC, |session| {
215 assert_eq!(session.branches().len(), 2);
216 assert_eq!(session.active_branch().entries().len(), 3);
217 });
218 let root = corpus.say(Role::User, "name the project");
219 corpus.say(Role::Assistant, "Forge");
220 let retry = corpus.message(Role::Assistant, vec![ContentBlock::text("Smith")]);
221 corpus.push_at(Some(root), &retry);
222 corpus.say(Role::User, "go with Smith");
223 corpus
224}
226fn corpora() -> [Corpus; 3] {
227 [linear_chat(), tool_compaction(), sibling_branches()]
228}
230fn trace_json(session: &Session) -> String {
231 let mut json = serde_json::to_string_pretty(&build_trace(session)).unwrap();
232 json.push('\n');
233 json
234}
236fn recorded_version(dir: &Path) -> Option<u16> {
237 let text = std::fs::read_to_string(dir.join("VERSION")).ok()?;
238 Some(text.trim().parse().unwrap())
239}
241/// Rewrite the corpus, refusing unless the entry frame version moved.
242fn regenerate(dir: &Path) {
243 let recorded = recorded_version(dir);
244 assert_ne!(
245 recorded,
246 Some(VERSION_ENTRY),
247 "refusing to regenerate: frame::VERSION_ENTRY is still {VERSION_ENTRY}; \
248 the golden corpus changes only with an entry frame version bump"
249 );
250 std::fs::create_dir_all(dir).unwrap();
251 for corpus in corpora() {
252 let path = dir.join(format!("{}.smh", corpus.name));
253 std::fs::write(&path, corpus.write()).unwrap();
254 let session = session_of(&path, corpus.name);
255 std::fs::write(
256 dir.join(format!("{}.trace.json", corpus.name)),
257 trace_json(&session),
258 )
259 .unwrap();
260 }
261 std::fs::write(dir.join("VERSION"), format!("{VERSION_ENTRY}\n")).unwrap();
262}
264/// Load the session file at `path`, asserting that it is undamaged and that
265/// re-encoding its frames reproduces it exactly.
266fn session_of(path: &Path, name: &str) -> Session {
267 let bytes = std::fs::read(path).unwrap();
268 let max = Config::default_valid().max_frame_bytes;
269 let recovery = load_session(path, max).unwrap();
270 assert!(recovery.damage.is_empty(), "{name}: {:?}", recovery.damage);
271 let reencoded: Vec<u8> = recovery
272 .frames
273 .iter()
274 .flat_map(|frame| frame.encode(max).unwrap())
275 .collect();
276 assert!(reencoded == bytes, "{name}: re-encoded frames differ");
277 Session::from_frames(&recovery.frames).unwrap()
278}
280/// Forking at the selected leaf keeps every record and its decoded content.
281fn assert_fork_at_leaf_preserves(session: &Session, name: &str) {
282 let leaf = session.selected_id().unwrap();
283 let fork = session.fork_at(leaf).unwrap();
284 let (original, forked) = (session.active_branch(), fork.active_branch());
285 assert_eq!(original.entries(), forked.entries(), "{name}: records");
286 assert_eq!(fork.selected_id(), Some(leaf), "{name}: selected leaf");
287 assert_eq!(
288 fork.compaction_boundary(),
289 session.compaction_boundary(),
290 "{name}: compaction boundary"
291 );
292 for (left, right) in original.entries().iter().zip(forked.entries()) {
293 assert_eq!(
294 session.content(left).unwrap(),
295 fork.content(right).unwrap(),
296 "{name}: entry {}",
297 left.id
298 );
299 }
300}
302#[test]
303fn corpus_replays_byte_identically() {
304 let dir = golden_dir();
305 match std::env::var(SWITCH).as_deref() {
306 Ok(REGENERATE) => regenerate(&dir),
307 Ok(other) => panic!("{SWITCH}={other}: the only value is {REGENERATE}"),
308 Err(_) => {}
309 }
310 assert_eq!(
311 recorded_version(&dir),
312 Some(VERSION_ENTRY),
313 "golden/VERSION must equal frame::VERSION_ENTRY; after a bump run \
314 `{SWITCH}={REGENERATE} cargo test -p smith-core --test golden`"
315 );
316 for corpus in corpora() {
317 let name = corpus.name;
318 let path = dir.join(format!("{name}.smh"));
319 let session = session_of(&path, name);
320 (corpus.shape)(&session);
321 let trace = std::fs::read_to_string(dir.join(format!("{name}.trace.json"))).unwrap();
322 assert!(trace_json(&session) == trace, "{name}: trace differs");
323 assert_fork_at_leaf_preserves(&session, name);
324 let stored = std::fs::read(&path).unwrap();
325 assert!(corpus.write() == stored, "{name}: writer output differs");
326 }
327}

smith-core/tests/golden/VERSION

Added
new file mode 100644

+1 / −0 text lines

smith-core/tests/golden/linear_chat.smh

Added
new file mode 100644

Binary size (old → new): 0 → 1549 bytes.

smith-core/tests/golden/linear_chat.trace.json

Added
new file mode 100644

+44 / −0 text lines

1[
2 {
3 "timestamp_ms": 0,
4 "session_id": "00000000-0000-000a-0000-000000005e55",
5 "kind": "SessionCreated",
6 "event_ref": "branch:00000000-0000-000a-0000-00000000b4a0"
7 },
8 {
9 "timestamp_ms": 1767225600000,
10 "session_id": "00000000-0000-000a-0000-000000005e55",
11 "kind": "MessageStreamed",
12 "event_ref": "message:00000000-0000-000a-0000-000200000001"
13 },
14 {
15 "timestamp_ms": 1767225601000,
16 "session_id": "00000000-0000-000a-0000-000000005e55",
17 "kind": "MessageStreamed",
18 "event_ref": "message:00000000-0000-000a-0000-000200000002"
19 },
20 {
21 "timestamp_ms": 1767225602000,
22 "session_id": "00000000-0000-000a-0000-000000005e55",
23 "kind": "MessageStreamed",
24 "event_ref": "message:00000000-0000-000a-0000-000200000003"
25 },
26 {
27 "timestamp_ms": 1767225603000,
28 "session_id": "00000000-0000-000a-0000-000000005e55",
29 "kind": "MessageStreamed",
30 "event_ref": "message:00000000-0000-000a-0000-000200000004"
31 },
32 {
33 "timestamp_ms": 1767225604000,
34 "session_id": "00000000-0000-000a-0000-000000005e55",
35 "kind": "MessageStreamed",
36 "event_ref": "message:00000000-0000-000a-0000-000200000005"
37 },
38 {
39 "timestamp_ms": 1767225605000,
40 "session_id": "00000000-0000-000a-0000-000000005e55",
41 "kind": "MessageStreamed",
42 "event_ref": "message:00000000-0000-000a-0000-000200000006"
43 }
44]

smith-core/tests/golden/sibling_branches.smh

Added
new file mode 100644

Binary size (old → new): 0 → 1035 bytes.

smith-core/tests/golden/sibling_branches.trace.json

Added
new file mode 100644

+26 / −0 text lines

1[
2 {
3 "timestamp_ms": 0,
4 "session_id": "00000000-0000-000c-0000-000000005e55",
5 "kind": "SessionCreated",
6 "event_ref": "branch:00000000-0000-000c-0000-00000000b4a0"
7 },
8 {
9 "timestamp_ms": 1767225600000,
10 "session_id": "00000000-0000-000c-0000-000000005e55",
11 "kind": "MessageStreamed",
12 "event_ref": "message:00000000-0000-000c-0000-000200000001"
13 },
14 {
15 "timestamp_ms": 1767225602000,
16 "session_id": "00000000-0000-000c-0000-000000005e55",
17 "kind": "MessageStreamed",
18 "event_ref": "message:00000000-0000-000c-0000-000200000003"
19 },
20 {
21 "timestamp_ms": 1767225603000,
22 "session_id": "00000000-0000-000c-0000-000000005e55",
23 "kind": "MessageStreamed",
24 "event_ref": "message:00000000-0000-000c-0000-000200000004"
25 }
26]

smith-core/tests/golden/tool_compaction.smh

Added
new file mode 100644

Binary size (old → new): 0 → 1975 bytes.

smith-core/tests/golden/tool_compaction.trace.json

Added
new file mode 100644

+56 / −0 text lines

1[
2 {
3 "timestamp_ms": 0,
4 "session_id": "00000000-0000-000b-0000-000000005e55",
5 "kind": "SessionCreated",
6 "event_ref": "branch:00000000-0000-000b-0000-00000000b4a0"
7 },
8 {
9 "timestamp_ms": 1767225600000,
10 "session_id": "00000000-0000-000b-0000-000000005e55",
11 "kind": "MessageStreamed",
12 "event_ref": "message:00000000-0000-000b-0000-000200000001"
13 },
14 {
15 "timestamp_ms": 1767225601000,
16 "session_id": "00000000-0000-000b-0000-000000005e55",
17 "kind": "MessageStreamed",
18 "event_ref": "message:00000000-0000-000b-0000-000200000002"
19 },
20 {
21 "timestamp_ms": 1767225602000,
22 "session_id": "00000000-0000-000b-0000-000000005e55",
23 "kind": "ToolCallEmitted",
24 "event_ref": "call:00000000-0000-000b-0000-000300000001"
25 },
26 {
27 "timestamp_ms": 1767225603000,
28 "session_id": "00000000-0000-000b-0000-000000005e55",
29 "kind": "ToolResultReceived",
30 "event_ref": "result:00000000-0000-000b-0000-000300000001:ok"
31 },
32 {
33 "timestamp_ms": 1767225604000,
34 "session_id": "00000000-0000-000b-0000-000000005e55",
35 "kind": "MessageStreamed",
36 "event_ref": "message:00000000-0000-000b-0000-000200000005"
37 },
38 {
39 "timestamp_ms": 1767225605000,
40 "session_id": "00000000-0000-000b-0000-000000005e55",
41 "kind": "Compaction",
42 "event_ref": "meta:compaction:00000000-0000-000b-0000-000100000006"
43 },
44 {
45 "timestamp_ms": 1767225606000,
46 "session_id": "00000000-0000-000b-0000-000000005e55",
47 "kind": "MessageStreamed",
48 "event_ref": "message:00000000-0000-000b-0000-000200000007"
49 },
50 {
51 "timestamp_ms": 1767225607000,
52 "session_id": "00000000-0000-000b-0000-000000005e55",
53 "kind": "MessageStreamed",
54 "event_ref": "message:00000000-0000-000b-0000-000200000008"
55 }
56]