feat(core): session arena; entry content as canonical CBOR bytes, frame v2, constant-allocation fork and load
819c23929d534147c7db7248786673d97e202514
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: e59fc110a436
There are many coding harnesses - but this one is fast
819c23929d534147c7db7248786673d97e202514
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+1132 / −565 text lines
+91 / −94 text lines
use crate::session::{COMPACTION_KIND, EntryContent, EntryKind, PROVIDER_HTTP_KIND}; out /// A masked copy of `message`: one allocation per text, never a /// plaintext intermediate. fn mask_message(&self, message: &Message) -> Message { let blocks = message .blocks .iter() .map(|block| match block { ContentBlock::Text(text) => ContentBlock::Text(self.mask(text)), ContentBlock::Thinking(text) => ContentBlock::Thinking(self.mask(text)), ContentBlock::ToolUse { name, input, call_id, } => ContentBlock::ToolUse { name: self.mask(name), input: self.mask_json(input), call_id: *call_id, }, ContentBlock::ToolResult { call_id, ok, output, } => ContentBlock::ToolResult { call_id: *call_id, ok: *ok, output: self.mask(output), }, }) .collect(); Message { id: message.id, role: message.role, blocks, timestamp_ms: message.timestamp_ms, /// Mask a decoded `message` in place; texts without a secret are not /// copied. fn mask_message(&self, message: &mut Message) { if self.registered.is_empty() { return; } for block in &mut message.blocks { match block { ContentBlock::Text(text) | ContentBlock::Thinking(text) => { self.mask_in_place(text); } ContentBlock::ToolUse { name, input, .. } => { self.mask_in_place(name); *input = self.mask_json(input); } ContentBlock::ToolResult { output, .. } => self.mask_in_place(output), } fn build_request(&self) -> ProviderRequest { // Requests carry the active branch since the compaction boundary. let since = self.tools.session.compaction_boundary; /// Decode the provider context into this request: the active branch's /// messages since the compaction boundary. This is the one per-request /// reader of entry content. fn build_request(&self) -> Result<ProviderRequest> { let session = &self.tools.session; let since = session.compaction_boundary; let EntryContent::Message(mut message) = session.content(entry)? else { return Err(SmithError::Session { code: "ENTRY_KIND_MISMATCH".to_string(), message: format!("message entry {} holds other content", entry.id), }); }; // Provider-bound context never receives registered plaintext. self.secrets.mask_message(&mut message); messages.push(message); let entry = crate::session::Entry::message(message, self.tools.session.selected_id()); if let Some(writer) = self.tools.writer_mut() { writer.append_frame(&crate::frame::Frame::Known { entry: entry.clone(), })?; } self.tools.session.append_to_active(entry); self.tools.record(&EntryContent::Message(message))?; let entry = crate::session::Entry::new( self.tools.session.selected_id(), crate::session::EntryContent::Meta { kind: crate::session::PROVIDER_HTTP_KIND.to_string(), detail, }, ); if let Some(writer) = self.tools.writer_mut() { writer.append_frame(&crate::frame::Frame::Known { entry: entry.clone(), })?; } self.tools.session.append_to_active(entry); use crate::session::Session; let recorded = format!("{:?}", agent.session().active_branch().entries); assert!(!format!("{:?}", agent.session().active_branch().entries).contains("s3cr3t-value"));+171 / −60 text lines
use crate::session::{Entry, SessionHeader};use crate::session::{Entry, EntryFrame, EntryWire, SessionHeader};pub const VERSION_ENTRY: u16 = 1; let mut limited = LimitedWriter::new(max_frame_bytes); let result = ciborium::ser::into_writer(value, &mut limited); if limited.overflowed() { return Err(too_large(max_frame_bytes, max_frame_bytes + 1)); } match result { Ok(()) => Ok(limited.into_inner()), Err(e) => Err(fault(FrameFault::Encode { message: e.to_string(), })), } serialize_limited(value, Vec::new(), max_frame_bytes) Self::encode_payload(entry, max_frame_bytes)?, (*kind, *version, payload.clone()) }; let declared = BODY_PREFIX_LEN + payload.len(); let mut body = Vec::with_capacity(declared); body.extend_from_slice(&kind.to_le_bytes()); body.extend_from_slice(&version.to_le_bytes()); body.extend_from_slice(&crc32(kind, version, &payload).to_le_bytes()); body.extend_from_slice(&payload); let Ok(prefix) = u32::try_from(declared) else { return Err(too_large(max_frame_bytes, payload.len())); }; let mut out = Vec::with_capacity(HEADER_LEN + declared); out.extend_from_slice(&prefix.to_le_bytes()); out.extend_from_slice(&body); Ok(out) }/// Encode a session record and its arena content bytes as a full entry/// frame, without copying the content out of the arena first.////// # Errors////// Returns a [`FrameFault::TooLarge`] or [`FrameFault::Encode`] error.pub fn encode_entry(entry: &Entry, content: &[u8], max_frame_bytes: usize) -> Result<Vec<u8>> { encode_frame( KIND_ENTRY, VERSION_ENTRY, &EntryWire::of(entry, content), content.len(), max_frame_bytes, )}/// Bytes before a frame payload: length prefix, kind, version, checksum.const FRAME_PREFIX_LEN: usize = HEADER_LEN + BODY_PREFIX_LEN;/// Capacity hint for the payload bytes of a frame beyond its entry content;/// an underestimate costs one reallocation, never correctness.const PAYLOAD_OVERHEAD_HINT: usize = 192;/// Serialize `value` as a frame payload directly after a reserved prefix, so/// one buffer holds the whole frame.fn encode_frame<T: serde::Serialize>( kind: u16, version: u16, value: &T, content_len: usize, max_frame_bytes: usize,) -> Result<Vec<u8>> { let capacity = (content_len + PAYLOAD_OVERHEAD_HINT).min(max_frame_bytes); let mut out = Vec::with_capacity(FRAME_PREFIX_LEN + capacity); out.resize(FRAME_PREFIX_LEN, 0); let out = serialize_limited(value, out, max_frame_bytes)?; seal(kind, version, out, max_frame_bytes)}/// Serialize `value` after the bytes already in `buf`, rejecting payloads/// above `max_frame_bytes` before unbounded allocation occurs.fn serialize_limited<T: serde::Serialize>( value: &T, buf: Vec<u8>, max_frame_bytes: usize,) -> Result<Vec<u8>> { let mut limited = LimitedWriter::new(buf, max_frame_bytes); let result = ciborium::ser::into_writer(value, &mut limited); if limited.overflowed() { return Err(too_large(max_frame_bytes, max_frame_bytes + 1)); } match result { Ok(()) => Ok(limited.into_inner()), Err(e) => Err(fault(FrameFault::Encode { message: e.to_string(), })), }}/// Fill the reserved prefix of `out` (length, kind, version, checksum) for/// the payload that follows it.fn seal(kind: u16, version: u16, mut out: Vec<u8>, max_frame_bytes: usize) -> Result<Vec<u8>> { let payload_len = out.len().saturating_sub(FRAME_PREFIX_LEN); let Ok(declared) = u32::try_from(BODY_PREFIX_LEN + payload_len) else { return Err(too_large(max_frame_bytes, payload_len)); }; let checksum = crc32(kind, version, &out[FRAME_PREFIX_LEN..]); out[..HEADER_LEN].copy_from_slice(&declared.to_le_bytes()); out[HEADER_LEN..HEADER_LEN + 2].copy_from_slice(&kind.to_le_bytes()); out[HEADER_LEN + 2..HEADER_LEN + 4].copy_from_slice(&version.to_le_bytes()); out[HEADER_LEN + 4..FRAME_PREFIX_LEN].copy_from_slice(&checksum.to_le_bytes()); Ok(out)} (KIND_ENTRY, VERSION_ENTRY) => decode_payload(payload).map(|entry| Frame::Known { entry }), const fn new(limit: usize) -> Self { use crate::session::{Entry, EntryContent}; use crate::session::{EntryContent, EntryKind, Session}; fn sample_entry(thinking: bool) -> Entry { entry: Entry::message(Message::with_text(Role::User, text), None), entry: message_frame(Message::with_text(Role::User, text)), Frame::Known { entry } => match &entry.content { Frame::Known { entry } => match EntryContent::decode(&entry.content).unwrap() { #[test] fn entry_frame_carries_kind_and_content_as_one_byte_string() { let call_id = ToolCallId::new(); let content = EntryContent::ToolResult { ok: true, output: "done".to_string(), call_id, }; let entry = EntryFrame::new(None, &content).unwrap(); assert_eq!(entry.kind, EntryKind::ToolResult { call_id, ok: true }); assert_eq!(EntryContent::decode(&entry.content).unwrap(), content); // The content is embedded verbatim after a CBOR byte-string header. let payload = Frame::encode_payload(&entry.wire(), DEFAULT_MAX_FRAME_BYTES).unwrap(); let at = payload .windows(entry.content.len()) .position(|window| window == entry.content.as_slice()) .unwrap(); let len = entry.content.len(); let header: &[u8] = if len < 24 { &[0x40 | len as u8] } else { &[0x58, len as u8] }; assert_eq!(&payload[at - header.len()..at], header); // A session record frames straight from arena bytes, identically. let mut session = Session::new(); let record = *session.append(None, &content).unwrap(); let from_arena = encode_entry(&record, session.bytes(&record), DEFAULT_MAX_FRAME_BYTES).unwrap(); let owned = Frame::Known { entry: EntryFrame { id: record.id, parent: record.parent, timestamp_ms: record.timestamp_ms, kind: record.kind, content: session.bytes(&record).to_vec(), }, }; assert_eq!(from_arena, owned.encode(DEFAULT_MAX_FRAME_BYTES).unwrap()); } let payload = Frame::encode_payload(&entry, DEFAULT_MAX_FRAME_BYTES).unwrap(); let payload = Frame::encode_payload(&entry.wire(), DEFAULT_MAX_FRAME_BYTES).unwrap();+8 / −5 text lines
+631 / −253 text lines
//! Branching session state, entries, and restoration from durable frames.//! Branching session state: an index arena of fixed-size entry records over//! one contiguous payload arena, plus restoration from durable frames.//!//! Entry content lives as canonical CBOR bytes, at rest and in memory. A//! record carries what traversal needs ([`EntryKind`]); anything else is a//! decode into the consuming scope.use crate::frame::Frame;/// Whether `value` already has the key order [`canonical_json`] produces.fn is_canonical(value: &serde_json::Value) -> bool { match value { serde_json::Value::Object(map) => { map.keys().zip(map.keys().skip(1)).all(|(a, b)| a < b) && map.values().all(is_canonical) } serde_json::Value::Array(items) => items.iter().all(is_canonical), _ => true, }}/// A session entry (message, tool call/result, or metadata).#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]/// Byte range of one entry's content in its session's payload arena.////// `u32` offsets cap one session arena at 4 GiB.#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]pub struct Span { /// First content byte. pub offset: u32, /// Content length in bytes. pub len: u32,}impl Span { /// The span of `len` bytes at `offset`, or an error past the arena cap. fn at(offset: usize, len: usize) -> Result<Self> { let full = || SmithError::Session { code: "SESSION_ARENA_FULL".to_string(), message: format!("entry content at {offset}+{len} exceeds the 4 GiB session arena"), }; let end = u32::try_from(offset.saturating_add(len)).map_err(|_| full())?; let offset = u32::try_from(offset).map_err(|_| full())?; Ok(Self { offset, len: end - offset, }) } const fn end(self) -> usize { self.offset as usize + self.len as usize } const fn range(self) -> std::ops::Range<usize> { self.offset as usize..self.end() }}/// What an entry recorded, reduced to the identifiers traversal pairs on.#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]pub enum EntryKind { /// Chat message. Message { /// Message identifier. id: MessageId, /// Who produced the message. role: Role, }, /// Tool call. ToolCall { /// Identifier pairing the call with its result. call_id: ToolCallId, }, /// Tool result. ToolResult { /// Identifier of the call this result answers. call_id: ToolCallId, /// Whether the effect succeeded. ok: bool, }, /// Session metadata. Meta { /// Whether the entry marks a compaction boundary. compaction: bool, },}/// A fixed-size session entry record; its content lives in the session/// payload arena.#[derive(Clone, Copy, PartialEq, Eq, Debug)]/// What one entry recorded.impl Entry { /// Whether this entry marks a compaction boundary. #[must_use] pub const fn is_compaction(&self) -> bool { matches!(self.kind, EntryKind::Meta { compaction: true }) }}/// Wire shape of one entry frame: the record plus its content as an opaque/// canonical CBOR byte string.#[derive(Clone, PartialEq, Eq, Debug, Deserialize)]pub struct EntryFrame { /// Entry ID. pub id: EntryId, /// Parent entry ID (None for root). pub parent: Option<EntryId>, /// Timestamp (Unix ms). pub timestamp_ms: i64, /// What the entry recorded. pub kind: EntryKind, /// Canonical CBOR of the [`EntryContent`]. #[serde(deserialize_with = "byte_buf")] pub content: Vec<u8>,}impl EntryFrame { /// A frame for `content` with a fresh identity, outside any session. /// /// # Errors /// /// Returns [`SmithError::Session`] when the content cannot be encoded. pub fn new(parent: Option<EntryId>, content: &EntryContent) -> Result<Self> { let mut bytes = Vec::new(); content.encode_into(&mut bytes)?; Ok(Self { id: EntryId::new(), parent, timestamp_ms: now_ms(), kind: content.kind(), content: bytes, }) } pub(crate) fn wire(&self) -> EntryWire<'_> { EntryWire { id: self.id, parent: self.parent, timestamp_ms: self.timestamp_ms, kind: self.kind, content: CborBytes(&self.content), } }}/// Borrowed serialization view of an entry frame, so arena bytes are/// framed without being copied out first.#[derive(Serialize)]pub(crate) struct EntryWire<'a> { id: EntryId, parent: Option<EntryId>, timestamp_ms: i64, kind: EntryKind, content: CborBytes<'a>,}impl<'a> EntryWire<'a> { pub(crate) const fn of(entry: &Entry, content: &'a [u8]) -> Self { Self { id: entry.id, parent: entry.parent, timestamp_ms: entry.timestamp_ms, kind: entry.kind, content: CborBytes(content), } }}/// Bytes serialized as one CBOR byte string rather than an integer array.struct CborBytes<'a>(&'a [u8]);impl Serialize for CborBytes<'_> { fn serialize<S: serde::Serializer>( &self, serializer: S, ) -> std::result::Result<S::Ok, S::Error> { serializer.serialize_bytes(self.0) }}fn byte_buf<'de, D: serde::Deserializer<'de>>( deserializer: D,) -> std::result::Result<Vec<u8>, D::Error> { struct Visitor; impl serde::de::Visitor<'_> for Visitor { type Value = Vec<u8>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("a byte string") } fn visit_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> std::result::Result<Vec<u8>, E> { Ok(bytes.to_vec()) } fn visit_byte_buf<E: serde::de::Error>( self, bytes: Vec<u8>, ) -> std::result::Result<Vec<u8>, E> { Ok(bytes) } } deserializer.deserialize_byte_buf(Visitor)}/// What one entry recorded; the decoded view of an entry's content./// 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)impl EntryContent { /// The record kind of this content. #[must_use] pub fn kind(&self) -> EntryKind { match self { Self::Message(message) => EntryKind::Message { id: message.id, role: message.role, }, Self::ToolCall { call_id, .. } => EntryKind::ToolCall { call_id: *call_id }, Self::ToolResult { call_id, ok, .. } => EntryKind::ToolResult { call_id: *call_id, ok: *ok, }, Self::Meta { kind, .. } => EntryKind::Meta { compaction: kind == COMPACTION_KIND, }, } } /// Decode content from its canonical CBOR bytes. /// /// # Errors /// /// Returns [`SmithError::Session`] when `bytes` are not entry content. pub fn decode(bytes: &[u8]) -> Result<Self> { ciborium::de::from_reader(bytes).map_err(|e| SmithError::Session { code: "ENTRY_DECODE".to_string(), message: e.to_string(), }) } /// Append the canonical CBOR of this content to `out`. This is the one /// place content is canonicalized. fn encode_into(&self, out: &mut Vec<u8>) -> Result<()> { ciborium::ser::into_writer(&*self.canonical(), out).map_err(|e| SmithError::Session { code: "ENTRY_ENCODE".to_string(), message: e.to_string(), }) } /// This content with every JSON value in canonical key order, borrowed /// when it already is. fn canonical(&self) -> Cow<'_, Self> { match self { Self::ToolCall { name, input, call_id, } if !is_canonical(input) => Cow::Owned(Self::ToolCall { name: name.clone(), input: canonical_json(input), call_id: *call_id, }), Self::Meta { kind, detail } if !is_canonical(detail) => Cow::Owned(Self::Meta { kind: kind.clone(), detail: canonical_json(detail), }), Self::Message(message) if !message.blocks.iter().all(|block| match block { ContentBlock::ToolUse { input, .. } => is_canonical(input), _ => true, }) => { let mut message = message.clone(); for block in &mut message.blocks { if let ContentBlock::ToolUse { input, .. } = block { *input = canonical_json(input); } } Cow::Owned(Self::Message(message)) } other => Cow::Borrowed(other), other @ EntryContent::ToolResult { .. } => other,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) }}#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]#[derive(Clone, PartialEq, Eq, Debug)]#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]#[derive(Clone, PartialEq, Eq, Debug)] payloads: Vec::new(), /// 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 /// Encode `content` once into the arena and append its record to the /// selected branch, selecting it. A compaction entry becomes the /// compaction boundary. /// /// # Errors /// /// Returns [`SmithError::Session`] when the content cannot be encoded or /// the arena is full; the session is unchanged then. pub fn append(&mut self, parent: Option<EntryId>, content: &EntryContent) -> Result<&Entry> { self.append_with(parent, content, |_, _| Ok(())) } /// [`Session::append`], running `persist` on the new record and its /// content bytes before the entry becomes part of the session. /// /// # Errors /// /// As [`Session::append`], or the error of `persist`; the session is /// unchanged then. pub fn append_with( &mut self, parent: Option<EntryId>, content: &EntryContent, persist: impl FnOnce(&Entry, &[u8]) -> Result<()>, ) -> Result<&Entry> { let offset = self.payloads.len(); let staged = content .encode_into(&mut self.payloads) .and_then(|()| Span::at(offset, self.payloads.len() - offset)) .map(|span| Entry { id: EntryId::new(), parent, timestamp_ms: now_ms(), kind: content.kind(), content: span, }) .and_then(|entry| persist(&entry, &self.payloads[offset..]).map(|()| entry)); let entry = match staged { Ok(entry) => entry, Err(error) => { self.payloads.truncate(offset); return Err(error); } }; if entry.is_compaction() { self.compaction_boundary = Some(entry.id); } let branch = self.active_branch_mut(); let idx = branch.append(entry); Ok(&branch.entries[idx]) } /// Append a compaction boundary entry after the selected entry and /// select it. Returns the record so callers can persist it. /// /// # Errors /// /// As [`Session::append`]. pub fn append_compaction(&mut self, detail: serde_json::Value) -> Result<Entry> { let content = EntryContent::Meta { kind: COMPACTION_KIND.to_string(), detail, }; self.append(self.selected_id(), &content).copied() } /// The canonical CBOR content bytes of `entry`; empty when `entry` does /// not belong to this session. #[must_use] pub fn bytes(&self, entry: &Entry) -> &[u8] { self.payloads.get(entry.content.range()).unwrap_or_default() } /// Decode the content of `entry` into the caller's scope. /// /// # Errors /// /// Returns [`SmithError::Session`] when the bytes do not decode. pub fn content(&self, entry: &Entry) -> Result<EntryContent> { EntryContent::decode(self.bytes(entry)) /// identity, because it is a different durable history. let selected_idx = entries.len().saturating_sub(1); payloads: self.payloads.get(..end).unwrap_or_default().to_vec(), /// /// Content bytes are copied into the arena, never decoded; every /// collection is sized up front, so a linear history restores with a /// constant number of allocations. /// /// # Errors /// /// Returns [`SmithError::Session`] when the content exceeds the arena cap. pub fn from_frames(frames: &[Frame]) -> Result<Self> { let (mut count, mut total) = (0, 0); Self::from_entries(header, &stored, boundary) Span::at(0, total)?; let mut payloads = Vec::with_capacity(total); let mut stored = Vec::with_capacity(count); let mut boundary = None; for frame in frames { let Frame::Known { entry } = frame else { continue; }; let record = Entry { id: entry.id, parent: entry.parent, timestamp_ms: entry.timestamp_ms, kind: entry.kind, content: Span::at(payloads.len(), entry.content.len())?, }; payloads.extend_from_slice(&entry.content); if record.is_compaction() { boundary = Some(record.id); } stored.push(record); } let header = header.unwrap_or_else(|| SessionHeader { session_id: SessionId::new(), branch_id: BranchId::new(), }); let (branches, active_branch_idx) = restore_branches(&stored, header.branch_id); Ok(Self { id: header.session_id, branches, payloads, active_branch_idx, compaction_boundary: 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/// Rebuild branches from stored records and their parent links, returning/// them with the index of the active branch.fn restore_branches(stored: &[Entry], active_id: BranchId) -> (Vec<Branch>, usize) { let Some(last) = stored.last() else { return (vec![Branch::with_id(active_id)], 0); }; // Entry id to its index and whether any stored entry names it as parent. let mut nodes: HashMap<EntryId, (usize, bool)> = HashMap::with_capacity(stored.len()); for (idx, entry) in stored.iter().enumerate() { nodes.insert(entry.id, (idx, false)); for parent in stored.iter().filter_map(|entry| entry.parent) { if let Some(node) = nodes.get_mut(&parent) { node.1 = true; } } let nodes = &nodes; let is_leaf = |entry: &&Entry| nodes.get(&entry.id).is_some_and(|node| !node.1); // Root-ward walk; a missing parent ends the recoverable chain, and the // step cap ends a corrupt cycle. let chain = |leaf: &Entry| { let mut cursor = Some(leaf.id); std::iter::from_fn(move || { let (idx, _) = nodes.get(&cursor?)?; let entry = stored.get(*idx)?; cursor = entry.parent; Some(*entry) }) .take(stored.len()) }; let mut branches = Vec::with_capacity(stored.iter().filter(is_leaf).count()); let mut active_branch_idx = 0; for leaf in stored.iter().filter(is_leaf) { let mut entries = Vec::with_capacity(chain(leaf).count()); entries.extend(chain(leaf)); entries.reverse(); 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 { active_id } else { BranchId::from_u128(leaf.id.as_u128()) }, selected_idx: entries.len().saturating_sub(1), entries, }); } (branches, active_branch_idx) fn frames(session: &Session) -> Vec<Frame> { 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); // Explicit parents record two children of one root. let mut scratch = Session::new(); let root = *scratch.append(None, &message("root")).unwrap(); let first = *scratch.append(Some(root.id), &message("first")).unwrap(); let second = *scratch.append(Some(root.id), &message("second")).unwrap(); let stored = frames(&scratch); let session = Session::from_frames(&stored).unwrap(); 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]; session.active_branch().branch_id, scratch.header().branch_id ); assert_eq!(ids(session.active_branch()), vec![root.id, second.id]); let sibling = &session.branches[1 - session.active_branch_idx]; assert_eq!(ids(sibling), vec![root.id, first.id]); // Shared-prefix records point at the same content bytes. assert_eq!( session.content(&sibling.entries[0]).unwrap(), scratch.content(&root).unwrap() let again = Session::from_entries(Some(header), &stored, None); let again = Session::from_frames(&stored).unwrap(); #[test] fn appended_content_decodes_from_the_arena_and_records_its_kind() { let mut session = Session::new(); let content = EntryContent::ToolResult { ok: false, output: "boom".to_string(), call_id: ToolCallId::new(), }; let entry = *session.append(None, &content).unwrap(); assert_eq!(entry.kind, content.kind()); assert_eq!(session.content(&entry).unwrap(), content); assert_eq!(session.bytes(&entry).len(), entry.content.len as usize); // A record from elsewhere reads as empty bytes and fails to decode. let foreign = Entry { content: Span { offset: 1 << 20, len: 4, }, ..entry }; assert!(session.bytes(&foreign).is_empty()); assert_eq!( session.content(&foreign).unwrap_err().code(), "ENTRY_DECODE" ); } #[test] fn failed_persist_leaves_the_session_unchanged() { let mut session = Session::new(); session.append(None, &message("kept")).unwrap(); let before = session.clone(); let err = session .append_with( session.selected_id(), &EntryContent::Meta { kind: COMPACTION_KIND.to_string(), detail: serde_json::json!({}), }, |_, bytes| { assert!(!bytes.is_empty()); Err(SmithError::Cancelled) }, ) .unwrap_err(); assert_eq!(err.code(), "CANCELLED"); assert_eq!(session, before); } assert_eq!( forked .active_branch() .entries .iter() .map(|entry| entry.id) .collect::<Vec<_>>(), vec![root.id, boundary.id] ); assert_eq!(ids(forked.active_branch()), vec![root.id, boundary.id]); message.add_block(smith::message::ContentBlock::ToolUse { message.add_block(ContentBlock::ToolUse { 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)); let root = message("root", None); let first = message("first", Some(root.id)); let second = message("second", Some(root.id)); let siblings = Session::from_entries(None, &[root.clone(), first.clone(), second], None); let mut scratch = Session::new(); let root = *scratch.append(None, &message("root")).unwrap(); let first = *scratch.append(Some(root.id), &message("first")).unwrap(); scratch.append(Some(root.id), &message("second")).unwrap(); let siblings = Session::from_frames(&frames(&scratch)).unwrap(); let ids: Vec<EntryId> = forked .active_branch() .entries .iter() .map(|e| e.id) .collect(); assert_eq!(ids, vec![root.id, first.id]); assert_eq!(ids(forked.active_branch()), vec![root.id, first.id]); assert_eq!(text_of(&forked, &forked.active_branch().entries[1]), "1"); } #[test] fn loading_copies_content_bytes_without_decoding_them() { let mut scratch = Session::new(); let root = *scratch.append(None, &message("root")).unwrap(); let mut stored = frames(&scratch); if let Frame::Known { entry } = &mut stored[1] { entry.content = vec![0xFF, 0x00]; } let restored = Session::from_frames(&stored).unwrap(); let record = restored.active_branch().entries[0]; assert_eq!(record.kind, root.kind); assert_eq!(restored.bytes(&record), &[0xFF, 0x00]); assert_eq!( restored.content(&record).unwrap_err().code(), "ENTRY_DECODE" ); assert_eq!(restored, session);+74 / −61 text lines
self.file.write_all(&bytes).map_err(io_err("STORE_WRITE"))?; self.write(&bytes) } /// Append one session record as an entry frame, framing its arena /// `content` bytes directly. Size limits apply as in /// [`SessionWriter::append_frame`]. /// /// # Errors /// /// Returns a framing error for oversized frames, or an input/output error. pub fn append_entry(&mut self, entry: &Entry, content: &[u8]) -> Result<()> { let bytes = encode_entry(entry, content, self.config.max_frame_bytes)?; self.write(&bytes) } fn write(&mut self, bytes: &[u8]) -> Result<()> { self.file.write_all(bytes).map_err(io_err("STORE_WRITE"))?; session: Session::from_frames(&recovery.frames), session: Session::from_frames(&recovery.frames)?, use crate::session::{Entry, EntryContent, Session}; use crate::session::{EntryContent, EntryFrame, EntryKind, Session}; fn message(text: &str) -> EntryContent { EntryContent::Message(Message::with_text(Role::User, text)) } fn entry(text: &str) -> EntryFrame { EntryFrame::new(None, &message(text)).unwrap() } fn text(entry: &EntryFrame) -> Option<String> { match EntryContent::decode(&entry.content).unwrap() { EntryContent::Message(m) => match &m.blocks[0] { ContentBlock::Text(t) => Some(t.clone()), _ => None, }, _ => None, } Frame::Known { entry } => match &entry.content { EntryContent::Message(m) => match &m.blocks[0] { ContentBlock::Text(t) => t.clone(), other => panic!("unexpected block {other:?}"), }, other => panic!("unexpected content {other:?}"), }, Frame::Known { entry } => text(entry).unwrap(), let second = Entry::message(Message::with_text(Role::User, "two"), Some(first.id)); let second = EntryFrame::new(Some(first.id), &message("two")).unwrap(); let session = Session::from_frames(&frames); let session = Session::from_frames(&frames).unwrap(); Frame::Known { entry } => match &entry.content { EntryContent::Message(m) => match &m.blocks[0] { ContentBlock::Text(t) => Some(t.clone()), _ => None, }, _ => None, }, Frame::Known { entry } => text(entry), Frame::Known { entry } => match &entry.content { EntryContent::Message(m) => match &m.blocks[0] { ContentBlock::Text(t) => assert_eq!(t, "known"), other => panic!("unexpected block {other:?}"), }, other => panic!("unexpected content {other:?}"), }, Frame::Known { entry } => assert_eq!(text(entry).as_deref(), Some("known")), let restored = Session::from_frames(&frames); let restored = Session::from_frames(&frames).unwrap(); let root = entry("root"); let root_id = root.id; opened.session.append_to_active(root.clone()); let root = *opened.session.append(None, &message("root")).unwrap(); .append_frame(&Frame::Known { entry: root }) .append_entry(&root, opened.session.bytes(&root)) .append_compaction(serde_json::json!({"kept": 1}));+39 / −38 text lines
use crate::frame::{Frame, canonical_json}; fn record_entry(&mut self, entry: Entry) -> Result<()> { if let Some(writer) = &mut self.writer { writer.append_frame(&Frame::Known { entry: entry.clone(), })?; } self.session.append_to_active(entry); Ok(()) /// Append `content` after the selected entry and durably record it /// first; a failed write leaves the session unchanged. pub(crate) fn record(&mut self, content: &EntryContent) -> Result<Entry> { let parent = self.session.selected_id(); let writer = self.writer.as_mut(); self.session .append_with(parent, content, |entry, bytes| { writer.map_or(Ok(()), |writer| writer.append_entry(entry, bytes)) }) .copied() use crate::session::EntryKind; .filter(|e| matches!(&e.content, EntryContent::ToolResult { ok: false, .. })) .filter(|e| matches!(e.kind, EntryKind::ToolResult { ok: false, .. }))+30 / −26 text lines
use crate::session::{EntryContent, Session};use crate::session::{COMPACTION_KIND, EntryKind, Session}; format!("result:{call_id}:{}", if *ok { "ok" } else { "failed" }), format!("result:{call_id}:{}", if ok { "ok" } else { "failed" }), tools.session.append_compaction(serde_json::json!({}));+81 / −22 text lines
/// `fork_at` over 1000 entries: the branch list, the chain `Vec`, and two allocations per cloned/// text entry (`blocks` and its `String`) until payloads become bytes at rest.const FORK_AT_1000_ALLOCATIONS: u64 = 2002;/// Scope counters are process-wide; measurements must not overlap.static MEASURING: Mutex<()> = Mutex::new(());/// `fork_at` over 1000 entries: the branch list, the record `Vec`, and one/// arena slice. Content bytes are copied, never decoded.const FORK_AT_1000_ALLOCATIONS: u64 = 3;/// `from_frames` over 1000 decoded frames: arena, stored records, the/// parent-link table, the branch list, and one branch's records, each sized/// up front. Independent of entry count.const FROM_FRAMES_1000_ALLOCATIONS: u64 = 5; ( ( after.allocations - before.allocations, after.bytes - before.bytes, ), out, )}/// Cost of one `fork_at` of the leaf.fn fork_cost(session: &Session) -> (u64, u64) { let leaf = session.selected_id().expect("non-empty session"); let (cost, fork) = session_cost(|| session.fork_at(leaf).expect("leaf is known")); let last = fork.active_branch().entries[fork.active_branch().entries.len() - 1]; assert_eq!(fork.bytes(&last), session.bytes(&last)); cost}/// Cost of restoring `session` from its decoded frames; frame decoding/// itself happens before the measured scope.fn from_frames_cost(session: &Session) -> (u64, u64) { let mut frames = vec![Frame::Header { header: session.header(), }]; frames.extend( session .active_branch() .entries .iter() .map(|entry| Frame::Known { entry: EntryFrame { id: entry.id, parent: entry.parent, timestamp_ms: entry.timestamp_ms, kind: entry.kind, content: session.bytes(entry).to_vec(), }, }), ); let (cost, restored) = session_cost(|| Session::from_frames(&frames).expect("frames restore")); assert_eq!(&restored, session); cost#[test]fn from_frames_allocates_independently_of_entry_count() { let small = from_frames_cost(&linear_session(100)); let large = from_frames_cost(&linear_session(1000)); assert_eq!( large.0, FROM_FRAMES_1000_ALLOCATIONS, "from_frames allocated {} times, bound is {FROM_FRAMES_1000_ALLOCATIONS}", large.0 ); assert_eq!(small.0, large.0); assert_eq!(large, from_frames_cost(&linear_session(1000)));}+6 / −5 text lines
+1 / −1 text lines