repositories / smith
smith
There are many coding harnesses - but this one is fast
owned by bugabinga
smith-core/src/session.rs
RawFile outline
- COMPACTION_KIND line 10
- PROVIDER_HTTP_KIND line 13
- canonical_json line 17
- SessionHeader line 38
- Entry line 47
- EntryContent line 60
- canonicalize line 94
- now_ms line 122
- Entry line 130
- new line 132
- message line 143
- compaction line 149
- is_compaction line 161
- Branch line 168
- Default for Branch line 178
- default line 179
- Branch line 184
- new line 186
- append line 196
- selected_entry line 203
- Session line 210
- Default for Session line 222
- default line 223
- Session line 228
- new line 230
- active_branch line 241
- active_branch_mut line 247
- append_to_active line 252
- selected_id line 258
- append_compaction line 265
- entries_by_id line 273
- ancestry line 283
- fork_at line 306
- header line 328
- from_frames line 344
- from_entries line 365
- tests line 423
- message line 434
- text_of line 438
- frames line 446
- sibling_entries_restore_as_separate_branches line 462
- fork_preserves_ids_order_leaf_and_compaction_boundary line 495
- tool_use_json_inside_messages_encodes_identically line 537
- fork_rejects_unknown_entries line 576
- compaction_boundary_survives_a_frame_round_trip line 583
//! Branching session state, entries, and restoration from durable frames.
use serde::{Deserialize, Serialize};
use smith::error::{Result, SmithError};
use smith::id::{BranchId, EntryId, SessionId, ToolCallId};
use smith::message::{ContentBlock, Message};
use std::collections::{HashMap, HashSet};
/// Meta entry kind that marks a compaction boundary.
pub const COMPACTION_KIND: &str = "compaction";
/// Metadata kind for one redacted provider HTTP effect record.
pub const PROVIDER_HTTP_KIND: &str = "provider-http";
/// Deterministic JSON: recursively sort object keys so equivalent values
/// encode to identical CBOR regardless of insertion order.
#[must_use]
pub fn canonical_json(value: &serde_json::Value) -> serde_json::Value {
match value {
serde_json::Value::Object(map) => {
let mut keys: Vec<&String> = map.keys().collect();
keys.sort();
let mut out = serde_json::Map::new();
for key in keys {
out.insert(key.clone(), canonical_json(&map[key]));
}
serde_json::Value::Object(out)
}
serde_json::Value::Array(items) => {
serde_json::Value::Array(items.iter().map(canonical_json).collect())
}
other => other.clone(),
}
}
/// Durable session identity, persisted as the first frame of a session file
/// so reload reproduces the same IDs instead of minting new ones.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct SessionHeader {
/// Session identifier.
pub session_id: SessionId,
/// Identifier of the root branch.
pub branch_id: BranchId,
}
/// A session entry (message, tool call/result, or metadata).
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Entry {
/// Entry ID.
pub id: EntryId,
/// Parent entry ID (None for root).
pub parent: Option<EntryId>,
/// Timestamp (Unix ms).
pub timestamp_ms: i64,
/// The content of the entry.
pub content: EntryContent,
}
/// What one entry recorded.
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[serde(tag = "kind", content = "data")]
pub enum EntryContent {
/// Chat message.
Message(Message),
/// Tool call (recorded for replay).
ToolCall {
/// Invoked tool.
name: String,
/// Canonical tool arguments.
input: serde_json::Value,
/// Identifier pairing this call with its result.
call_id: ToolCallId,
},
/// Tool result.
ToolResult {
/// Whether the effect succeeded.
ok: bool,
/// Recorded output or error text.
output: String,
/// Identifier of the call this result answers.
call_id: ToolCallId,
},
/// Session metadata event (compaction, branch selection).
Meta {
/// Metadata kind, for example [`COMPACTION_KIND`].
kind: String,
/// Kind-specific payload.
detail: serde_json::Value,
},
}
/// Canonicalize every JSON value an entry carries, so equivalent entries
/// encode identically no matter how their objects were built.
fn canonicalize(content: EntryContent) -> EntryContent {
match content {
EntryContent::ToolCall {
name,
input,
call_id,
} => EntryContent::ToolCall {
name,
input: canonical_json(&input),
call_id,
},
EntryContent::Meta { kind, detail } => EntryContent::Meta {
kind,
detail: canonical_json(&detail),
},
EntryContent::Message(mut message) => {
for block in &mut message.blocks {
if let ContentBlock::ToolUse { input, .. } = block {
*input = canonical_json(input);
}
}
EntryContent::Message(message)
}
other @ EntryContent::ToolResult { .. } => other,
}
}
/// Wall-clock milliseconds since the Unix epoch, saturating on overflow.
fn now_ms() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |elapsed| {
i64::try_from(elapsed.as_millis()).unwrap_or(i64::MAX)
})
}
impl Entry {
/// A new entry with canonical content and a fresh identity.
#[must_use]
pub fn new(parent: Option<EntryId>, content: EntryContent) -> Self {
Self {
id: EntryId::new(),
parent,
timestamp_ms: now_ms(),
content: canonicalize(content),
}
}
/// A message entry.
#[must_use]
pub fn message(msg: Message, parent: Option<EntryId>) -> Self {
Self::new(parent, EntryContent::Message(msg))
}
/// A compaction boundary entry. `detail` records what was summarized.
#[must_use]
pub fn compaction(parent: Option<EntryId>, detail: serde_json::Value) -> Self {
Self::new(
parent,
EntryContent::Meta {
kind: COMPACTION_KIND.to_string(),
detail,
},
)
}
/// Whether this entry marks a compaction boundary.
#[must_use]
pub fn is_compaction(&self) -> bool {
matches!(&self.content, EntryContent::Meta { kind, .. } if kind == COMPACTION_KIND)
}
}
/// Selected branch in a session.
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Branch {
/// Branch ID.
pub branch_id: BranchId,
/// Entries ordered by time.
pub entries: Vec<Entry>,
/// Index of selected leaf.
pub selected_idx: usize,
}
impl Default for Branch {
fn default() -> Self {
Self::new()
}
}
impl Branch {
/// An empty branch with a fresh identity.
#[must_use]
pub fn new() -> Self {
Self {
branch_id: BranchId::new(),
entries: Vec::new(),
selected_idx: 0,
}
}
/// Append `entry` and select it. Returns its index.
pub fn append(&mut self, entry: Entry) -> usize {
self.entries.push(entry);
self.selected_idx = self.entries.len().saturating_sub(1);
self.selected_idx
}
/// The currently selected entry, if the branch has any.
#[must_use]
pub fn selected_entry(&self) -> Option<&Entry> {
self.entries.get(self.selected_idx)
}
}
/// A session is a persistent, branching message/tool history.
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Session {
/// Session identifier.
pub id: SessionId,
/// All branches (default branch is index 0).
pub branches: Vec<Branch>,
/// Index of active branch.
pub active_branch_idx: usize,
/// Compaction boundary entry (if any).
pub compaction_boundary: Option<EntryId>,
}
impl Default for Session {
fn default() -> Self {
Self::new()
}
}
impl Session {
/// A new session with one empty branch.
#[must_use]
pub fn new() -> Self {
Self {
id: SessionId::new(),
branches: vec![Branch::new()],
active_branch_idx: 0,
compaction_boundary: None,
}
}
/// The selected branch.
#[must_use]
pub fn active_branch(&self) -> &Branch {
&self.branches[self.active_branch_idx]
}
/// The selected branch, mutably.
pub fn active_branch_mut(&mut self) -> &mut Branch {
&mut self.branches[self.active_branch_idx]
}
/// Append `entry` to the selected branch and select it.
pub fn append_to_active(&mut self, entry: Entry) {
let branch = self.active_branch_mut();
branch.append(entry);
}
/// Identifier of the selected entry, if any.
#[must_use]
pub fn selected_id(&self) -> Option<EntryId> {
self.active_branch().selected_entry().map(|e| e.id)
}
/// Append a compaction boundary entry to the active branch and select it.
/// Returns the entry so callers can persist it.
pub fn append_compaction(&mut self, detail: serde_json::Value) -> Entry {
let entry = Entry::compaction(self.selected_id(), detail);
self.compaction_boundary = Some(entry.id);
self.append_to_active(entry.clone());
entry
}
/// Every entry of this session, regardless of branch.
fn entries_by_id(&self) -> HashMap<EntryId, &Entry> {
self.branches
.iter()
.flat_map(|branch| branch.entries.iter())
.map(|entry| (entry.id, entry))
.collect()
}
/// The root-to-`at` entry chain, or `None` when `at` is unknown or its
/// ancestry is broken.
fn ancestry(&self, at: EntryId) -> Option<Vec<Entry>> {
let known = self.entries_by_id();
let mut chain = Vec::new();
let mut cursor = Some(at);
while let Some(id) = cursor {
let entry = known.get(&id)?;
chain.push((*entry).clone());
cursor = entry.parent;
}
chain.reverse();
Some(chain)
}
/// Fork the history ending at `at` into a new session.
///
/// Entry IDs, order, and timestamps are preserved, `at` becomes the
/// selected leaf, and the compaction boundary carries over when it lies
/// on the retained path. The new session gets fresh session and branch
/// identity, because it is a different durable history.
///
/// # Errors
///
/// Returns [`SmithError::Session`] when `at` is not part of this session.
pub fn fork_at(&self, at: EntryId) -> Result<Self> {
let entries = self.ancestry(at).ok_or_else(|| SmithError::Session {
code: "ENTRY_NOT_FOUND".to_string(),
message: format!("entry {at} is not part of session {}", self.id),
})?;
let boundary = self
.compaction_boundary
.filter(|id| entries.iter().any(|entry| entry.id == *id));
let selected_idx = entries.len().saturating_sub(1);
Ok(Self {
id: SessionId::new(),
branches: vec![Branch {
branch_id: BranchId::new(),
entries,
selected_idx,
}],
active_branch_idx: 0,
compaction_boundary: boundary,
})
}
/// The durable identity of this session's active branch.
#[must_use]
pub fn header(&self) -> SessionHeader {
SessionHeader {
session_id: self.id,
branch_id: self.active_branch().branch_id,
}
}
/// Restore in-memory state from decoded frames.
///
/// A header frame restores the session and branch identity, so state
/// rebuilt from the same file is identical on every load. Stored parent
/// links define the branches: each entry with no children is a leaf, and
/// its root-to-leaf chain is one branch. The last stored entry is the
/// selected leaf of the active branch. Unknown frames are skipped here,
/// and compaction entries restore the compaction boundary.
#[must_use]
pub fn from_frames(frames: &[crate::frame::Frame]) -> Self {
let mut header = None;
let mut stored: Vec<Entry> = Vec::new();
let mut boundary = None;
for frame in frames {
match frame {
crate::frame::Frame::Header { header: found } => header = Some(*found),
crate::frame::Frame::Known { entry } => {
if entry.is_compaction() {
boundary = Some(entry.id);
}
stored.push(entry.clone());
}
crate::frame::Frame::Unknown { .. } => {}
}
}
Self::from_entries(header, &stored, boundary)
}
/// Rebuild branches from stored entries and their parent links.
fn from_entries(
header: Option<SessionHeader>,
stored: &[Entry],
boundary: Option<EntryId>,
) -> Self {
let mut session = Self::new();
if let Some(header) = header {
session.id = header.session_id;
session.active_branch_mut().branch_id = header.branch_id;
}
session.compaction_boundary = boundary;
if stored.is_empty() {
return session;
}
let parents: HashSet<EntryId> = stored.iter().filter_map(|entry| entry.parent).collect();
let known: HashMap<EntryId, &Entry> =
stored.iter().map(|entry| (entry.id, entry)).collect();
let last_id = stored[stored.len() - 1].id;
let mut branches = Vec::new();
let mut active_branch_idx = 0;
for leaf in stored.iter().filter(|entry| !parents.contains(&entry.id)) {
let mut entries = Vec::new();
let mut cursor = Some(leaf.id);
// Walk to the root; a missing parent ends the recoverable chain.
while let Some(id) = cursor {
match known.get(&id) {
Some(entry) => {
entries.push((*entry).clone());
cursor = entry.parent;
}
None => break,
}
}
entries.reverse();
let selected_idx = entries.len().saturating_sub(1);
let is_active = leaf.id == last_id;
if is_active {
active_branch_idx = branches.len();
}
branches.push(Branch {
// The selected branch owns the persisted identity; sibling
// branches derive theirs from their leaf, which keeps every
// reload of the same file identical.
branch_id: if is_active {
session.active_branch().branch_id
} else {
BranchId::from_u128(leaf.id.as_u128())
},
entries,
selected_idx,
});
}
session.branches = branches;
session.active_branch_idx = active_branch_idx;
session
}
}
#[cfg(test)]
#[expect(
clippy::unwrap_used,
clippy::panic,
reason = "tests may panic on invariant violations"
)]
mod tests {
use super::*;
use crate::frame::Frame;
use smith::message::Role;
fn message(text: &str, parent: Option<EntryId>) -> Entry {
Entry::message(Message::with_text(Role::User, text), parent)
}
fn text_of(entry: &Entry) -> String {
match &entry.content {
EntryContent::Message(m) => format!("{}", m.blocks.len()),
EntryContent::Meta { kind, .. } => kind.clone(),
other => panic!("unexpected content {other:?}"),
}
}
fn frames(session: &Session) -> Vec<Frame> {
let mut frames = vec![Frame::Header {
header: session.header(),
}];
frames.extend(
session
.active_branch()
.entries
.iter()
.map(|entry| Frame::Known {
entry: entry.clone(),
}),
);
frames
}
#[test]
fn sibling_entries_restore_as_separate_branches() {
let root = message("root", None);
let first = message("first", Some(root.id));
let second = message("second", Some(root.id));
let stored = vec![root.clone(), first.clone(), second.clone()];
let header = SessionHeader {
session_id: SessionId::new(),
branch_id: BranchId::new(),
};
let session = Session::from_entries(Some(header), &stored, None);
assert_eq!(session.branches.len(), 2);
// The last stored entry selects the active branch and keeps the
// persisted branch identity.
assert_eq!(session.selected_id(), Some(second.id));
assert_eq!(session.active_branch().branch_id, header.branch_id);
let ids: Vec<EntryId> = session
.active_branch()
.entries
.iter()
.map(|entry| entry.id)
.collect();
assert_eq!(ids, vec![root.id, second.id]);
let sibling = &session.branches[1 - session.active_branch_idx];
assert_eq!(
sibling.entries.iter().map(|e| e.id).collect::<Vec<_>>(),
vec![root.id, first.id]
);
// Reconstruction is identical on a second pass, sibling ids included.
let again = Session::from_entries(Some(header), &stored, None);
assert_eq!(again, session);
}
#[test]
fn fork_preserves_ids_order_leaf_and_compaction_boundary() {
let mut session = Session::new();
let root = message("root", None);
session.append_to_active(root.clone());
let boundary = session.append_compaction(serde_json::json!({"summarized": 1}));
let after = message("after", Some(boundary.id));
session.append_to_active(after.clone());
let forked = session.fork_at(boundary.id).unwrap();
assert_ne!(forked.id, session.id);
assert_eq!(
forked
.active_branch()
.entries
.iter()
.map(|entry| entry.id)
.collect::<Vec<_>>(),
vec![root.id, boundary.id]
);
assert_eq!(forked.selected_id(), Some(boundary.id));
assert_eq!(forked.compaction_boundary, Some(boundary.id));
assert_eq!(
forked
.active_branch()
.entries
.iter()
.map(text_of)
.collect::<Vec<_>>(),
vec!["1".to_string(), COMPACTION_KIND.to_string()]
);
// Forking before the boundary drops it, because it is not retained.
let earlier = session.fork_at(root.id).unwrap();
assert_eq!(earlier.compaction_boundary, None);
assert_eq!(earlier.active_branch().entries.len(), 1);
// The source session is untouched.
assert_eq!(session.active_branch().entries.len(), 3);
assert_eq!(session.selected_id(), Some(after.id));
}
#[test]
fn tool_use_json_inside_messages_encodes_identically() {
let call_id = smith::id::ToolCallId::new();
let block = |input: serde_json::Value| {
let mut message = Message::with_text(Role::Assistant, "call");
message.add_block(smith::message::ContentBlock::ToolUse {
name: "write".to_string(),
input,
call_id,
});
message
};
let mut first = Entry::message(
block(serde_json::json!({"path": "p", "content": "c"})),
None,
);
let mut second = Entry::message(
block(serde_json::json!({"content": "c", "path": "p"})),
None,
);
// Only key order may differ, so encodings must match.
second.id = first.id;
second.timestamp_ms = first.timestamp_ms;
if let (EntryContent::Message(a), EntryContent::Message(b)) =
(&mut first.content, &mut second.content)
{
b.id = a.id;
b.timestamp_ms = a.timestamp_ms;
}
let encode = |entry: &Entry| {
Frame::Known {
entry: entry.clone(),
}
.encode(1 << 20)
.unwrap()
};
assert_eq!(encode(&first), encode(&second));
}
#[test]
fn fork_rejects_unknown_entries() {
let session = Session::new();
let err = session.fork_at(EntryId::new()).unwrap_err();
assert_eq!(err.code(), "ENTRY_NOT_FOUND");
}
#[test]
fn compaction_boundary_survives_a_frame_round_trip() {
let mut session = Session::new();
session.append_to_active(message("root", None));
let boundary = session.append_compaction(serde_json::json!({}));
let restored = Session::from_frames(&frames(&session));
assert_eq!(restored.compaction_boundary, Some(boundary.id));
assert_eq!(restored.id, session.id);
assert_eq!(
restored.active_branch().branch_id,
session.header().branch_id
);
}
}