repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

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

Browse filesCompare with HEAD

Changed files (10)

+1132 / −565 text lines

Diff layout

smith-core/src/agent.rs

Modified

+91 / −94 text lines

66//! turns with ordered, paired durable events. Vendor details stop at the
77//! [`StreamFn`](smith::provider::StreamFn) it consumes.
9use crate::session::{COMPACTION_KIND, EntryContent, EntryKind, PROVIDER_HTTP_KIND};
910use crate::tools::ToolSession;
1011use smith::error::{Result, SmithError};
1112use smith::id::ToolCallId;
143144 #[must_use]
144145 pub fn mask(&self, text: &str) -> String {
145146 let mut out = text.to_string();
147 self.mask_in_place(&mut out);
148 out
149 }
151 /// [`SecretProxy::mask`] without a copy when `text` holds no secret.
152 fn mask_in_place(&self, text: &mut String) {
146153 for (name, value) in &self.registered {
147 if !value.is_empty() && out.contains(value.as_str()) {
148 out = out.replace(value.as_str(), &Self::placeholder(name));
154 if !value.is_empty() && text.contains(value.as_str()) {
155 *text = text.replace(value.as_str(), &Self::placeholder(name));
149156 }
150157 }
151 out
152158 }
154160 fn transform_json(
173179 }
174180 }
176 /// A masked copy of `message`: one allocation per text, never a
177 /// plaintext intermediate.
178 fn mask_message(&self, message: &Message) -> Message {
179 let blocks = message
180 .blocks
181 .iter()
182 .map(|block| match block {
183 ContentBlock::Text(text) => ContentBlock::Text(self.mask(text)),
184 ContentBlock::Thinking(text) => ContentBlock::Thinking(self.mask(text)),
185 ContentBlock::ToolUse {
186 name,
187 input,
188 call_id,
189 } => ContentBlock::ToolUse {
190 name: self.mask(name),
191 input: self.mask_json(input),
192 call_id: *call_id,
193 },
194 ContentBlock::ToolResult {
195 call_id,
196 ok,
197 output,
198 } => ContentBlock::ToolResult {
199 call_id: *call_id,
200 ok: *ok,
201 output: self.mask(output),
202 },
203 })
204 .collect();
205 Message {
206 id: message.id,
207 role: message.role,
208 blocks,
209 timestamp_ms: message.timestamp_ms,
182 /// Mask a decoded `message` in place; texts without a secret are not
183 /// copied.
184 fn mask_message(&self, message: &mut Message) {
185 if self.registered.is_empty() {
186 return;
187 }
188 for block in &mut message.blocks {
189 match block {
190 ContentBlock::Text(text) | ContentBlock::Thinking(text) => {
191 self.mask_in_place(text);
192 }
193 ContentBlock::ToolUse { name, input, .. } => {
194 self.mask_in_place(name);
195 *input = self.mask_json(input);
196 }
197 ContentBlock::ToolResult { output, .. } => self.mask_in_place(output),
198 }
210199 }
211200 }
457446 });
458447 }
459448 let masked = self.secrets.mask(&summary.text);
460 let entry = self.tools.session.append_compaction(serde_json::json!({
461 "summary": masked,
462 "complete": true,
463 }));
464 if let Some(writer) = self.tools.writer_mut() {
465 writer.append_frame(&crate::frame::Frame::Known {
466 entry: entry.clone(),
467 })?;
468 }
449 let entry = self.tools.record(&EntryContent::Meta {
450 kind: COMPACTION_KIND.to_string(),
451 detail: serde_json::json!({
452 "summary": masked,
453 "complete": true,
454 }),
455 })?;
469456 Ok(entry.id)
470457 }
505492 loop {
506493 self.check_cancelled()?;
507494 self.deliver_between_request_queue()?;
508 let request = self.build_request();
495 let request = self.build_request()?;
509496 let stream = (self.stream)(request, self.cancel.clone());
510497 let Round {
511498 text,
651638 Ok(round)
652639 }
654 fn build_request(&self) -> ProviderRequest {
655 // Requests carry the active branch since the compaction boundary.
656 let since = self.tools.session.compaction_boundary;
641 /// Decode the provider context into this request: the active branch's
642 /// messages since the compaction boundary. This is the one per-request
643 /// reader of entry content.
644 fn build_request(&self) -> Result<ProviderRequest> {
645 let session = &self.tools.session;
646 let since = session.compaction_boundary;
657647 let mut messages = Vec::new();
658648 let mut include = since.is_none();
659 for entry in &self.tools.session.active_branch().entries {
660 if let Some(boundary) = since
661 && boundary == entry.id
662 {
649 for entry in &session.active_branch().entries {
650 if since == Some(entry.id) {
663651 include = true;
664652 continue;
665653 }
666 if include && let crate::session::EntryContent::Message(message) = &entry.content {
667 // Provider-bound context never receives registered plaintext.
668 messages.push(self.secrets.mask_message(message));
654 if !include || !matches!(entry.kind, EntryKind::Message { .. }) {
655 continue;
669656 }
657 let EntryContent::Message(mut message) = session.content(entry)? else {
658 return Err(SmithError::Session {
659 code: "ENTRY_KIND_MISMATCH".to_string(),
660 message: format!("message entry {} holds other content", entry.id),
661 });
662 };
663 // Provider-bound context never receives registered plaintext.
664 self.secrets.mask_message(&mut message);
665 messages.push(message);
670666 }
671667 let mut request = ProviderRequest::new(self.model.clone(), messages);
672668 request.tools = self.tools.registered_tools();
673 request
669 Ok(request)
674670 }
676672 fn record_user_message(&mut self, text: &str) -> Result<()> {
678674 }
680676 fn record_message(&mut self, message: Message) -> Result<()> {
681 let entry = crate::session::Entry::message(message, self.tools.session.selected_id());
682 if let Some(writer) = self.tools.writer_mut() {
683 writer.append_frame(&crate::frame::Frame::Known {
684 entry: entry.clone(),
685 })?;
686 }
687 self.tools.session.append_to_active(entry);
677 self.tools.record(&EntryContent::Message(message))?;
688678 Ok(())
689679 }
697687 // Records are drained in bulk before any session entry is built.
698688 let drained: Vec<serde_json::Value> = drain.try_iter().collect();
699689 for detail in drained {
700 let entry = crate::session::Entry::new(
701 self.tools.session.selected_id(),
702 crate::session::EntryContent::Meta {
703 kind: crate::session::PROVIDER_HTTP_KIND.to_string(),
704 detail,
705 },
706 );
707 if let Some(writer) = self.tools.writer_mut() {
708 writer.append_frame(&crate::frame::Frame::Known {
709 entry: entry.clone(),
710 })?;
711 }
712 self.tools.session.append_to_active(entry);
690 self.tools.record(&EntryContent::Meta {
691 kind: PROVIDER_HTTP_KIND.to_string(),
692 detail,
693 })?;
713694 }
714695 Ok(())
715696 }
745726)]
746727mod tests {
747728 use super::*;
729 use crate::session::Session;
748730 use crate::store::open_session;
749731 use futures::StreamExt;
750732 use smith::config::Config;
770752 (stream, seen)
771753 }
755 /// Every decoded entry content, rendered for secret checks.
756 fn decoded(session: &Session) -> String {
757 let contents: Vec<EntryContent> = session
758 .active_branch()
759 .entries
760 .iter()
761 .map(|entry| session.content(entry).unwrap())
762 .collect();
763 format!("{contents:?}")
764 }
773766 fn temp_tools(tag: &str) -> ToolSession {
774767 let dir = std::env::temp_dir().join(format!("smith_agent_{tag}_{}", std::process::id()));
775768 let _ = std::fs::remove_dir_all(&dir);
824817 .active_branch()
825818 .entries
826819 .iter()
827 .map(|entry| match &entry.content {
828 crate::session::EntryContent::Message(message) => match message.role {
820 .map(|entry| match entry.kind {
821 EntryKind::Message { role, .. } => match role {
829822 Role::User => "user",
830823 Role::Assistant => "assistant",
831824 Role::Tool => "tool",
832825 Role::System => "system",
833826 },
834 crate::session::EntryContent::ToolCall { .. } => "call",
835 crate::session::EntryContent::ToolResult { .. } => "result",
836 crate::session::EntryContent::Meta { .. } => "meta",
827 EntryKind::ToolCall { .. } => "call",
828 EntryKind::ToolResult { .. } => "result",
829 EntryKind::Meta { .. } => "meta",
837830 })
838831 .collect();
839832 assert_eq!(
913906 .active_branch()
914907 .entries
915908 .iter()
916 .filter_map(|entry| match entry.content {
917 crate::session::EntryContent::ToolCall { call_id, .. }
918 | crate::session::EntryContent::ToolResult { call_id, .. } => Some(call_id),
909 .filter_map(|entry| match entry.kind {
910 EntryKind::ToolCall { call_id } | EntryKind::ToolResult { call_id, .. } => {
911 Some(call_id)
912 }
919913 _ => None,
920914 })
921915 .collect();
952946 .active_branch()
953947 .entries
954948 .iter()
955 .map(|entry| match &entry.content {
956 crate::session::EntryContent::ToolCall { .. } => "call",
957 crate::session::EntryContent::ToolResult { .. } => "result",
949 .map(|entry| match entry.kind {
950 EntryKind::ToolCall { .. } => "call",
951 EntryKind::ToolResult { .. } => "result",
958952 _ => "other",
959953 })
960954 .collect();
10571051 assert!(!dispatched.contains("s3cr3t-value"));
10581052 drop(requests);
1060 let recorded = format!("{:?}", agent.session().active_branch().entries);
1054 let recorded = decoded(agent.session());
1055 assert!(recorded.contains("{{secret:api_key}}"));
10611056 assert!(!recorded.contains("s3cr3t-value"));
10621057 assert_eq!(
10631058 std::fs::read_to_string(secret_path).unwrap(),
11101105 .any(|window| window == b"s3cr3t-value")
11111106 );
11121107 let reopened = open_session(&path, Config::default_valid()).unwrap();
1113 assert!(
1114 !format!("{:?}", reopened.session.active_branch().entries).contains("s3cr3t-value")
1115 );
1108 let restored = decoded(&reopened.session);
1109 assert!(restored.contains("{{secret:api_key}}"));
1110 assert!(!restored.contains("s3cr3t-value"));
11161111 let _ = std::fs::remove_dir_all(&dir);
11531148 assert!(!tool_error.contains("s3cr3t-value"));
11541149 drop(requests);
1156 assert!(!format!("{:?}", agent.session().active_branch().entries).contains("s3cr3t-value"));
1151 let recorded = decoded(agent.session());
1152 assert!(recorded.contains("{{secret:api_key}}"));
1153 assert!(!recorded.contains("s3cr3t-value"));
11591156 #[test]

smith-core/src/frame.rs

Modified

+171 / −60 text lines

1212//! and payload, which is what keeps corruption distinguishable from a frame
1313//! kind that a future build introduced.
15use crate::session::{Entry, SessionHeader};
15use crate::session::{Entry, EntryFrame, EntryWire, SessionHeader};
1616use smith::error::{FrameFault, Result, SmithError};
1717use std::io::{Read, Write};
2929pub const KIND_ENTRY: u16 = 1;
3131/// Supported version of the [`KIND_ENTRY`] payload schema.
32pub const VERSION_ENTRY: u16 = 1;
32/// Version 2 carries the content as an opaque canonical CBOR byte string.
33pub const VERSION_ENTRY: u16 = 2;
3435/// Frame kind of the session header payload.
3536pub const KIND_SESSION_HEADER: u16 = 2;
5051 },
5152 /// A known session entry.
5253 Known {
53 /// Decoded entry.
54 entry: Entry,
54 /// Decoded entry frame; its content stays canonical CBOR bytes.
55 entry: EntryFrame,
5556 },
5657 /// A checksum-valid frame of a kind this build does not know.
5758 /// Kind, version, and payload are preserved so it round-trips unchanged.
7677 value: &T,
7778 max_frame_bytes: usize,
7879 ) -> Result<Vec<u8>> {
79 let mut limited = LimitedWriter::new(max_frame_bytes);
80 let result = ciborium::ser::into_writer(value, &mut limited);
81 if limited.overflowed() {
82 return Err(too_large(max_frame_bytes, max_frame_bytes + 1));
83 }
84 match result {
85 Ok(()) => Ok(limited.into_inner()),
86 Err(e) => Err(fault(FrameFault::Encode {
87 message: e.to_string(),
88 })),
89 }
80 serialize_limited(value, Vec::new(), max_frame_bytes)
9081 }
9283 /// Encode the full frame (length prefix, body prefix, payload) enforcing
9687 ///
9788 /// Returns a [`FrameFault::TooLarge`] or [`FrameFault::Encode`] error.
9889 pub fn encode(&self, max_frame_bytes: usize) -> Result<Vec<u8>> {
99 let (kind, version, payload) = match self {
100 Self::Header { header } => (
90 match self {
91 Self::Header { header } => encode_frame(
10192 KIND_SESSION_HEADER,
10293 VERSION_SESSION_HEADER,
103 Self::encode_payload(header, max_frame_bytes)?,
94 header,
95 0,
96 max_frame_bytes,
10497 ),
105 Self::Known { entry } => (
98 Self::Known { entry } => encode_frame(
10699 KIND_ENTRY,
107100 VERSION_ENTRY,
108 Self::encode_payload(entry, max_frame_bytes)?,
101 &entry.wire(),
102 entry.content.len(),
103 max_frame_bytes,
109104 ),
110105 Self::Unknown {
111106 kind,
115110 if payload.len() > max_frame_bytes {
116111 return Err(too_large(max_frame_bytes, payload.len()));
117112 }
118 (*kind, *version, payload.clone())
113 let mut out = Vec::with_capacity(FRAME_PREFIX_LEN + payload.len());
114 out.resize(FRAME_PREFIX_LEN, 0);
115 out.extend_from_slice(payload);
116 seal(*kind, *version, out, max_frame_bytes)
119117 }
120 };
121 let declared = BODY_PREFIX_LEN + payload.len();
122 let mut body = Vec::with_capacity(declared);
123 body.extend_from_slice(&kind.to_le_bytes());
124 body.extend_from_slice(&version.to_le_bytes());
125 body.extend_from_slice(&crc32(kind, version, &payload).to_le_bytes());
126 body.extend_from_slice(&payload);
127 let Ok(prefix) = u32::try_from(declared) else {
128 return Err(too_large(max_frame_bytes, payload.len()));
129 };
130 let mut out = Vec::with_capacity(HEADER_LEN + declared);
131 out.extend_from_slice(&prefix.to_le_bytes());
132 out.extend_from_slice(&body);
133 Ok(out)
118 }
134119 }
122/// Encode a session record and its arena content bytes as a full entry
123/// frame, without copying the content out of the arena first.
124///
125/// # Errors
126///
127/// Returns a [`FrameFault::TooLarge`] or [`FrameFault::Encode`] error.
128pub fn encode_entry(entry: &Entry, content: &[u8], max_frame_bytes: usize) -> Result<Vec<u8>> {
129 encode_frame(
130 KIND_ENTRY,
131 VERSION_ENTRY,
132 &EntryWire::of(entry, content),
133 content.len(),
134 max_frame_bytes,
135 )
136}
138/// Bytes before a frame payload: length prefix, kind, version, checksum.
139const FRAME_PREFIX_LEN: usize = HEADER_LEN + BODY_PREFIX_LEN;
141/// Capacity hint for the payload bytes of a frame beyond its entry content;
142/// an underestimate costs one reallocation, never correctness.
143const PAYLOAD_OVERHEAD_HINT: usize = 192;
145/// Serialize `value` as a frame payload directly after a reserved prefix, so
146/// one buffer holds the whole frame.
147fn encode_frame<T: serde::Serialize>(
148 kind: u16,
149 version: u16,
150 value: &T,
151 content_len: usize,
152 max_frame_bytes: usize,
153) -> Result<Vec<u8>> {
154 let capacity = (content_len + PAYLOAD_OVERHEAD_HINT).min(max_frame_bytes);
155 let mut out = Vec::with_capacity(FRAME_PREFIX_LEN + capacity);
156 out.resize(FRAME_PREFIX_LEN, 0);
157 let out = serialize_limited(value, out, max_frame_bytes)?;
158 seal(kind, version, out, max_frame_bytes)
159}
161/// Serialize `value` after the bytes already in `buf`, rejecting payloads
162/// above `max_frame_bytes` before unbounded allocation occurs.
163fn serialize_limited<T: serde::Serialize>(
164 value: &T,
165 buf: Vec<u8>,
166 max_frame_bytes: usize,
167) -> Result<Vec<u8>> {
168 let mut limited = LimitedWriter::new(buf, max_frame_bytes);
169 let result = ciborium::ser::into_writer(value, &mut limited);
170 if limited.overflowed() {
171 return Err(too_large(max_frame_bytes, max_frame_bytes + 1));
172 }
173 match result {
174 Ok(()) => Ok(limited.into_inner()),
175 Err(e) => Err(fault(FrameFault::Encode {
176 message: e.to_string(),
177 })),
178 }
179}
181/// Fill the reserved prefix of `out` (length, kind, version, checksum) for
182/// the payload that follows it.
183fn seal(kind: u16, version: u16, mut out: Vec<u8>, max_frame_bytes: usize) -> Result<Vec<u8>> {
184 let payload_len = out.len().saturating_sub(FRAME_PREFIX_LEN);
185 let Ok(declared) = u32::try_from(BODY_PREFIX_LEN + payload_len) else {
186 return Err(too_large(max_frame_bytes, payload_len));
187 };
188 let checksum = crc32(kind, version, &out[FRAME_PREFIX_LEN..]);
189 out[..HEADER_LEN].copy_from_slice(&declared.to_le_bytes());
190 out[HEADER_LEN..HEADER_LEN + 2].copy_from_slice(&kind.to_le_bytes());
191 out[HEADER_LEN + 2..HEADER_LEN + 4].copy_from_slice(&version.to_le_bytes());
192 out[HEADER_LEN + 4..FRAME_PREFIX_LEN].copy_from_slice(&checksum.to_le_bytes());
193 Ok(out)
194}
137196/// Classify one frame body: verify the checksum first, then the kind and
138197/// version, then the payload schema.
139198fn decode_body(body: &[u8]) -> std::result::Result<Frame, FrameFault> {
152211 });
153212 }
154213 match (kind, version) {
155 (KIND_ENTRY, VERSION_ENTRY) => decode_payload(payload).map(|entry| Frame::Known { entry }),
214 (KIND_ENTRY, VERSION_ENTRY) => {
215 decode_payload(payload).map(|entry: EntryFrame| Frame::Known { entry })
216 }
156217 (KIND_SESSION_HEADER, VERSION_SESSION_HEADER) => {
157218 decode_payload(payload).map(|header| Frame::Header { header })
158219 }
360421impl LimitedWriter {
361 const fn new(limit: usize) -> Self {
422 /// Accept up to `limit` bytes after the ones already in `buf`.
423 const fn new(buf: Vec<u8>, limit: usize) -> Self {
362424 Self {
363 buf: Vec::new(),
425 buf,
364426 remaining: limit,
365427 overflow: false,
366428 }
413475)]
414476mod tests {
415477 use super::*;
416 use crate::session::{Entry, EntryContent};
478 use crate::session::{EntryContent, EntryKind, Session};
417479 use smith::id::ToolCallId;
418480 use smith::message::{ContentBlock, Message, Role};
420 fn sample_entry(thinking: bool) -> Entry {
482 fn message_frame(message: Message) -> EntryFrame {
483 EntryFrame::new(None, &EntryContent::Message(message)).unwrap()
484 }
486 fn sample_entry(thinking: bool) -> EntryFrame {
421487 let mut msg = Message::with_text(Role::User, "hello");
422488 if thinking {
423489 msg.add_block(ContentBlock::thinking("internal"));
424490 }
425 Entry::message(msg, None)
491 message_frame(msg)
426492 }
428494 fn known_bytes(text: &str) -> Vec<u8> {
429495 Frame::Known {
430 entry: Entry::message(Message::with_text(Role::User, text), None),
496 entry: message_frame(Message::with_text(Role::User, text)),
431497 }
432498 .encode(DEFAULT_MAX_FRAME_BYTES)
433499 .unwrap()
436502 fn text_of(frame: &Frame) -> String {
437503 match frame {
438 Frame::Known { entry } => match &entry.content {
504 Frame::Known { entry } => match EntryContent::decode(&entry.content).unwrap() {
439505 EntryContent::Message(m) => match &m.blocks[0] {
440506 ContentBlock::Text(t) => t.clone(),
441507 other => panic!("unexpected block {other:?}"),
509575 assert_eq!(recovery.good_end, bytes.len() as u64);
510576 }
578 #[test]
579 fn entry_frame_carries_kind_and_content_as_one_byte_string() {
580 let call_id = ToolCallId::new();
581 let content = EntryContent::ToolResult {
582 ok: true,
583 output: "done".to_string(),
584 call_id,
585 };
586 let entry = EntryFrame::new(None, &content).unwrap();
587 assert_eq!(entry.kind, EntryKind::ToolResult { call_id, ok: true });
588 assert_eq!(EntryContent::decode(&entry.content).unwrap(), content);
589 // The content is embedded verbatim after a CBOR byte-string header.
590 let payload = Frame::encode_payload(&entry.wire(), DEFAULT_MAX_FRAME_BYTES).unwrap();
591 let at = payload
592 .windows(entry.content.len())
593 .position(|window| window == entry.content.as_slice())
594 .unwrap();
595 let len = entry.content.len();
596 let header: &[u8] = if len < 24 {
597 &[0x40 | len as u8]
598 } else {
599 &[0x58, len as u8]
600 };
601 assert_eq!(&payload[at - header.len()..at], header);
603 // A session record frames straight from arena bytes, identically.
604 let mut session = Session::new();
605 let record = *session.append(None, &content).unwrap();
606 let from_arena =
607 encode_entry(&record, session.bytes(&record), DEFAULT_MAX_FRAME_BYTES).unwrap();
608 let owned = Frame::Known {
609 entry: EntryFrame {
610 id: record.id,
611 parent: record.parent,
612 timestamp_ms: record.timestamp_ms,
613 kind: record.kind,
614 content: session.bytes(&record).to_vec(),
615 },
616 };
617 assert_eq!(from_arena, owned.encode(DEFAULT_MAX_FRAME_BYTES).unwrap());
618 }
512620 #[test]
513621 fn torn_tail_is_located_and_earlier_frames_kept() {
514622 let mut bytes = known_bytes("kept");
610718 fn version_one_frames_without_body_prefix_are_rejected() {
611719 // Old layout: [len][CBOR payload] with no kind, version, or checksum.
612720 let entry = sample_entry(false);
613 let payload = Frame::encode_payload(&entry, DEFAULT_MAX_FRAME_BYTES).unwrap();
721 let payload = Frame::encode_payload(&entry.wire(), DEFAULT_MAX_FRAME_BYTES).unwrap();
614722 let mut bytes = u32::try_from(payload.len()).unwrap().to_le_bytes().to_vec();
615723 bytes.extend_from_slice(&payload);
616724 let recovery = read_all(&bytes, DEFAULT_MAX_FRAME_BYTES);
633741 #[test]
634742 fn encoding_rejects_frames_above_limit() {
635 let big = Entry::message(
636 {
637 let mut m = Message::with_text(Role::User, "x");
638 m.add_block(ContentBlock::text("y".repeat(4096)));
639 m
640 },
641 None,
642 );
743 let big = message_frame({
744 let mut m = Message::with_text(Role::User, "x");
745 m.add_block(ContentBlock::text("y".repeat(4096)));
746 m
747 });
643748 let err = Frame::Known { entry: big }.encode(64).unwrap_err();
644749 assert_eq!(err.code(), "FRAME_TOO_LARGE");
645750 }
647752 #[test]
648753 fn equivalent_inputs_encode_identically_despite_key_order() {
649 let a = canonical_json(&serde_json::json!({"path": "p", "content": "c"}));
650 let b = canonical_json(&serde_json::json!({"content": "c", "path": "p"}));
754 let a = serde_json::json!({"path": "p", "content": {"b": 1, "a": 2}});
755 let b = serde_json::json!({"content": {"a": 2, "b": 1}, "path": "p"});
756 assert_eq!(
757 canonical_json(&a).to_string(),
758 canonical_json(&b).to_string()
759 );
651760 let call_id = ToolCallId::new();
652 let e1 = Entry::new(
761 let e1 = EntryFrame::new(
653762 None,
654 EntryContent::ToolCall {
763 &EntryContent::ToolCall {
655764 name: "write".into(),
656765 input: a,
657766 call_id,
658767 },
659 );
660 let mut e2 = Entry::new(
768 )
769 .unwrap();
770 let mut e2 = EntryFrame::new(
661771 None,
662 EntryContent::ToolCall {
772 &EntryContent::ToolCall {
663773 name: "write".into(),
664774 input: b,
665775 call_id,
666776 },
667 );
777 )
778 .unwrap();
668779 // Force identical ids/timestamps so only key order could differ.
669780 e2.id = e1.id;
670781 e2.timestamp_ms = e1.timestamp_ms;

smith-core/src/lib.rs

Modified

+8 / −5 text lines

2424 Agent, AgentEvent, CompactionSummary, Delivery, QueuedInput, SecretProxy, TurnOutcome,
2525};
2626pub use bash::{BashResult, execute};
27pub use frame::{Frame, Recovery, read_frames, write_frame};
28pub use session::{Branch, COMPACTION_KIND, Entry, EntryContent, Session, SessionHeader};
27pub use frame::{Frame, Recovery, encode_entry, read_frames, write_frame};
28pub use session::{
29 Branch, COMPACTION_KIND, Entry, EntryContent, EntryFrame, EntryKind, Session, SessionHeader,
30 Span,
31};
2932pub use store::{
3033 OpenSession, SessionWriter, create_session, fork_session, load_session, open_session,
3134 repair_session,
4245 fn session_creates_and_appends() {
4346 let mut session = Session::new();
4447 let msg = Message::with_text(Role::User, "hello");
45 let entry = Entry::message(msg, None);
46 session.append_to_active(entry);
47 assert_eq!(session.active_branch().entries.len(), 1);
48 let entry = *session.append(None, &EntryContent::Message(msg)).unwrap();
49 assert_eq!(session.active_branch().entries, vec![entry]);
50 assert_eq!(session.selected_id(), Some(entry.id));
4851 }

smith-core/src/session.rs

Modified

+631 / −253 text lines

1//! Branching session state, entries, and restoration from durable frames.
1//! Branching session state: an index arena of fixed-size entry records over
2//! one contiguous payload arena, plus restoration from durable frames.
3//!
4//! Entry content lives as canonical CBOR bytes, at rest and in memory. A
5//! record carries what traversal needs ([`EntryKind`]); anything else is a
6//! decode into the consuming scope.
8use crate::frame::Frame;
39use serde::{Deserialize, Serialize};
410use smith::error::{Result, SmithError};
5use smith::id::{BranchId, EntryId, SessionId, ToolCallId};
6use smith::message::{ContentBlock, Message};
7use std::collections::{HashMap, HashSet};
11use smith::id::{BranchId, EntryId, MessageId, SessionId, ToolCallId};
12use smith::message::{ContentBlock, Message, Role};
13use std::borrow::Cow;
14use std::collections::HashMap;
916/// Meta entry kind that marks a compaction boundary.
1017pub const COMPACTION_KIND: &str = "compaction";
3340 }
43/// Whether `value` already has the key order [`canonical_json`] produces.
44fn is_canonical(value: &serde_json::Value) -> bool {
45 match value {
46 serde_json::Value::Object(map) => {
47 map.keys().zip(map.keys().skip(1)).all(|(a, b)| a < b) && map.values().all(is_canonical)
48 }
49 serde_json::Value::Array(items) => items.iter().all(is_canonical),
50 _ => true,
51 }
52}
3654/// Durable session identity, persisted as the first frame of a session file
3755/// so reload reproduces the same IDs instead of minting new ones.
3856#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
4361 pub branch_id: BranchId,
46/// A session entry (message, tool call/result, or metadata).
47#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
64/// Byte range of one entry's content in its session's payload arena.
65///
66/// `u32` offsets cap one session arena at 4 GiB.
67#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
68pub struct Span {
69 /// First content byte.
70 pub offset: u32,
71 /// Content length in bytes.
72 pub len: u32,
73}
75impl Span {
76 /// The span of `len` bytes at `offset`, or an error past the arena cap.
77 fn at(offset: usize, len: usize) -> Result<Self> {
78 let full = || SmithError::Session {
79 code: "SESSION_ARENA_FULL".to_string(),
80 message: format!("entry content at {offset}+{len} exceeds the 4 GiB session arena"),
81 };
82 let end = u32::try_from(offset.saturating_add(len)).map_err(|_| full())?;
83 let offset = u32::try_from(offset).map_err(|_| full())?;
84 Ok(Self {
85 offset,
86 len: end - offset,
87 })
88 }
90 const fn end(self) -> usize {
91 self.offset as usize + self.len as usize
92 }
94 const fn range(self) -> std::ops::Range<usize> {
95 self.offset as usize..self.end()
96 }
97}
99/// What an entry recorded, reduced to the identifiers traversal pairs on.
100#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
101pub enum EntryKind {
102 /// Chat message.
103 Message {
104 /// Message identifier.
105 id: MessageId,
106 /// Who produced the message.
107 role: Role,
108 },
109 /// Tool call.
110 ToolCall {
111 /// Identifier pairing the call with its result.
112 call_id: ToolCallId,
113 },
114 /// Tool result.
115 ToolResult {
116 /// Identifier of the call this result answers.
117 call_id: ToolCallId,
118 /// Whether the effect succeeded.
119 ok: bool,
120 },
121 /// Session metadata.
122 Meta {
123 /// Whether the entry marks a compaction boundary.
124 compaction: bool,
125 },
126}
128/// A fixed-size session entry record; its content lives in the session
129/// payload arena.
130#[derive(Clone, Copy, PartialEq, Eq, Debug)]
48131pub struct Entry {
49132 /// Entry ID.
50133 pub id: EntryId,
52135 pub parent: Option<EntryId>,
53136 /// Timestamp (Unix ms).
54137 pub timestamp_ms: i64,
55 /// The content of the entry.
56 pub content: EntryContent,
138 /// What the entry recorded.
139 pub kind: EntryKind,
140 /// Canonical CBOR of the [`EntryContent`], in the session arena.
141 pub content: Span,
59/// What one entry recorded.
144impl Entry {
145 /// Whether this entry marks a compaction boundary.
146 #[must_use]
147 pub const fn is_compaction(&self) -> bool {
148 matches!(self.kind, EntryKind::Meta { compaction: true })
149 }
150}
152/// Wire shape of one entry frame: the record plus its content as an opaque
153/// canonical CBOR byte string.
154#[derive(Clone, PartialEq, Eq, Debug, Deserialize)]
155pub struct EntryFrame {
156 /// Entry ID.
157 pub id: EntryId,
158 /// Parent entry ID (None for root).
159 pub parent: Option<EntryId>,
160 /// Timestamp (Unix ms).
161 pub timestamp_ms: i64,
162 /// What the entry recorded.
163 pub kind: EntryKind,
164 /// Canonical CBOR of the [`EntryContent`].
165 #[serde(deserialize_with = "byte_buf")]
166 pub content: Vec<u8>,
167}
169impl EntryFrame {
170 /// A frame for `content` with a fresh identity, outside any session.
171 ///
172 /// # Errors
173 ///
174 /// Returns [`SmithError::Session`] when the content cannot be encoded.
175 pub fn new(parent: Option<EntryId>, content: &EntryContent) -> Result<Self> {
176 let mut bytes = Vec::new();
177 content.encode_into(&mut bytes)?;
178 Ok(Self {
179 id: EntryId::new(),
180 parent,
181 timestamp_ms: now_ms(),
182 kind: content.kind(),
183 content: bytes,
184 })
185 }
187 pub(crate) fn wire(&self) -> EntryWire<'_> {
188 EntryWire {
189 id: self.id,
190 parent: self.parent,
191 timestamp_ms: self.timestamp_ms,
192 kind: self.kind,
193 content: CborBytes(&self.content),
194 }
195 }
196}
198/// Borrowed serialization view of an entry frame, so arena bytes are
199/// framed without being copied out first.
200#[derive(Serialize)]
201pub(crate) struct EntryWire<'a> {
202 id: EntryId,
203 parent: Option<EntryId>,
204 timestamp_ms: i64,
205 kind: EntryKind,
206 content: CborBytes<'a>,
207}
209impl<'a> EntryWire<'a> {
210 pub(crate) const fn of(entry: &Entry, content: &'a [u8]) -> Self {
211 Self {
212 id: entry.id,
213 parent: entry.parent,
214 timestamp_ms: entry.timestamp_ms,
215 kind: entry.kind,
216 content: CborBytes(content),
217 }
218 }
219}
221/// Bytes serialized as one CBOR byte string rather than an integer array.
222struct CborBytes<'a>(&'a [u8]);
224impl Serialize for CborBytes<'_> {
225 fn serialize<S: serde::Serializer>(
226 &self,
227 serializer: S,
228 ) -> std::result::Result<S::Ok, S::Error> {
229 serializer.serialize_bytes(self.0)
230 }
231}
233fn byte_buf<'de, D: serde::Deserializer<'de>>(
234 deserializer: D,
235) -> std::result::Result<Vec<u8>, D::Error> {
236 struct Visitor;
237 impl serde::de::Visitor<'_> for Visitor {
238 type Value = Vec<u8>;
240 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
241 formatter.write_str("a byte string")
242 }
244 fn visit_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> std::result::Result<Vec<u8>, E> {
245 Ok(bytes.to_vec())
246 }
248 fn visit_byte_buf<E: serde::de::Error>(
249 self,
250 bytes: Vec<u8>,
251 ) -> std::result::Result<Vec<u8>, E> {
252 Ok(bytes)
253 }
254 }
255 deserializer.deserialize_byte_buf(Visitor)
256}
258/// What one entry recorded; the decoded view of an entry's content.
60259#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
61260#[serde(tag = "kind", content = "data")]
62261pub enum EntryContent {
89288 },
92/// Canonicalize every JSON value an entry carries, so equivalent entries
93/// encode identically no matter how their objects were built.
94fn canonicalize(content: EntryContent) -> EntryContent {
95 match content {
96 EntryContent::ToolCall {
97 name,
98 input,
99 call_id,
100 } => EntryContent::ToolCall {
101 name,
102 input: canonical_json(&input),
103 call_id,
104 },
105 EntryContent::Meta { kind, detail } => EntryContent::Meta {
106 kind,
107 detail: canonical_json(&detail),
108 },
109 EntryContent::Message(mut message) => {
110 for block in &mut message.blocks {
111 if let ContentBlock::ToolUse { input, .. } = block {
112 *input = canonical_json(input);
113 }
114 }
115 EntryContent::Message(message)
291impl EntryContent {
292 /// The record kind of this content.
293 #[must_use]
294 pub fn kind(&self) -> EntryKind {
295 match self {
296 Self::Message(message) => EntryKind::Message {
297 id: message.id,
298 role: message.role,
299 },
300 Self::ToolCall { call_id, .. } => EntryKind::ToolCall { call_id: *call_id },
301 Self::ToolResult { call_id, ok, .. } => EntryKind::ToolResult {
302 call_id: *call_id,
303 ok: *ok,
304 },
305 Self::Meta { kind, .. } => EntryKind::Meta {
306 compaction: kind == COMPACTION_KIND,
307 },
308 }
309 }
311 /// Decode content from its canonical CBOR bytes.
312 ///
313 /// # Errors
314 ///
315 /// Returns [`SmithError::Session`] when `bytes` are not entry content.
316 pub fn decode(bytes: &[u8]) -> Result<Self> {
317 ciborium::de::from_reader(bytes).map_err(|e| SmithError::Session {
318 code: "ENTRY_DECODE".to_string(),
319 message: e.to_string(),
320 })
321 }
323 /// Append the canonical CBOR of this content to `out`. This is the one
324 /// place content is canonicalized.
325 fn encode_into(&self, out: &mut Vec<u8>) -> Result<()> {
326 ciborium::ser::into_writer(&*self.canonical(), out).map_err(|e| SmithError::Session {
327 code: "ENTRY_ENCODE".to_string(),
328 message: e.to_string(),
329 })
330 }
332 /// This content with every JSON value in canonical key order, borrowed
333 /// when it already is.
334 fn canonical(&self) -> Cow<'_, Self> {
335 match self {
336 Self::ToolCall {
337 name,
338 input,
339 call_id,
340 } if !is_canonical(input) => Cow::Owned(Self::ToolCall {
341 name: name.clone(),
342 input: canonical_json(input),
343 call_id: *call_id,
344 }),
345 Self::Meta { kind, detail } if !is_canonical(detail) => Cow::Owned(Self::Meta {
346 kind: kind.clone(),
347 detail: canonical_json(detail),
348 }),
349 Self::Message(message)
350 if !message.blocks.iter().all(|block| match block {
351 ContentBlock::ToolUse { input, .. } => is_canonical(input),
352 _ => true,
353 }) =>
354 {
355 let mut message = message.clone();
356 for block in &mut message.blocks {
357 if let ContentBlock::ToolUse { input, .. } = block {
358 *input = canonical_json(input);
359 }
360 }
361 Cow::Owned(Self::Message(message))
362 }
363 other => Cow::Borrowed(other),
116364 }
117 other @ EntryContent::ToolResult { .. } => other,
118365 }
127374 })
130impl Entry {
131 /// A new entry with canonical content and a fresh identity.
132 #[must_use]
133 pub fn new(parent: Option<EntryId>, content: EntryContent) -> Self {
134 Self {
135 id: EntryId::new(),
136 parent,
137 timestamp_ms: now_ms(),
138 content: canonicalize(content),
139 }
140 }
142 /// A message entry.
143 #[must_use]
144 pub fn message(msg: Message, parent: Option<EntryId>) -> Self {
145 Self::new(parent, EntryContent::Message(msg))
146 }
148 /// A compaction boundary entry. `detail` records what was summarized.
149 #[must_use]
150 pub fn compaction(parent: Option<EntryId>, detail: serde_json::Value) -> Self {
151 Self::new(
152 parent,
153 EntryContent::Meta {
154 kind: COMPACTION_KIND.to_string(),
155 detail,
156 },
157 )
158 }
160 /// Whether this entry marks a compaction boundary.
161 #[must_use]
162 pub fn is_compaction(&self) -> bool {
163 matches!(&self.content, EntryContent::Meta { kind, .. } if kind == COMPACTION_KIND)
164 }
165}
167377/// Selected branch in a session.
168#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
378#[derive(Clone, PartialEq, Eq, Debug)]
169379pub struct Branch {
170380 /// Branch ID.
171381 pub branch_id: BranchId,
172 /// Entries ordered by time.
382 /// Entry records ordered root to leaf.
173383 pub entries: Vec<Entry>,
174384 /// Index of selected leaf.
175385 pub selected_idx: usize,
185395 /// An empty branch with a fresh identity.
186396 #[must_use]
187397 pub fn new() -> Self {
398 Self::with_id(BranchId::new())
399 }
401 const fn with_id(branch_id: BranchId) -> Self {
188402 Self {
189 branch_id: BranchId::new(),
403 branch_id,
190404 entries: Vec::new(),
191405 selected_idx: 0,
192406 }
209423/// A session is a persistent, branching message/tool history.
210#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
424#[derive(Clone, PartialEq, Eq, Debug)]
211425pub struct Session {
212426 /// Session identifier.
213427 pub id: SessionId,
214428 /// All branches (default branch is index 0).
215429 pub branches: Vec<Branch>,
430 /// Canonical CBOR content of every entry, addressed by [`Span`].
431 payloads: Vec<u8>,
216432 /// Index of active branch.
217433 pub active_branch_idx: usize,
218434 /// Compaction boundary entry (if any).
232448 Self {
233449 id: SessionId::new(),
234450 branches: vec![Branch::new()],
451 payloads: Vec::new(),
235452 active_branch_idx: 0,
236453 compaction_boundary: None,
237454 }
248465 &mut self.branches[self.active_branch_idx]
249466 }
251 /// Append `entry` to the selected branch and select it.
252 pub fn append_to_active(&mut self, entry: Entry) {
253 let branch = self.active_branch_mut();
254 branch.append(entry);
255 }
257468 /// Identifier of the selected entry, if any.
258469 #[must_use]
259470 pub fn selected_id(&self) -> Option<EntryId> {
260471 self.active_branch().selected_entry().map(|e| e.id)
261472 }
263 /// Append a compaction boundary entry to the active branch and select it.
264 /// Returns the entry so callers can persist it.
265 pub fn append_compaction(&mut self, detail: serde_json::Value) -> Entry {
266 let entry = Entry::compaction(self.selected_id(), detail);
267 self.compaction_boundary = Some(entry.id);
268 self.append_to_active(entry.clone());
269 entry
474 /// Encode `content` once into the arena and append its record to the
475 /// selected branch, selecting it. A compaction entry becomes the
476 /// compaction boundary.
477 ///
478 /// # Errors
479 ///
480 /// Returns [`SmithError::Session`] when the content cannot be encoded or
481 /// the arena is full; the session is unchanged then.
482 pub fn append(&mut self, parent: Option<EntryId>, content: &EntryContent) -> Result<&Entry> {
483 self.append_with(parent, content, |_, _| Ok(()))
484 }
486 /// [`Session::append`], running `persist` on the new record and its
487 /// content bytes before the entry becomes part of the session.
488 ///
489 /// # Errors
490 ///
491 /// As [`Session::append`], or the error of `persist`; the session is
492 /// unchanged then.
493 pub fn append_with(
494 &mut self,
495 parent: Option<EntryId>,
496 content: &EntryContent,
497 persist: impl FnOnce(&Entry, &[u8]) -> Result<()>,
498 ) -> Result<&Entry> {
499 let offset = self.payloads.len();
500 let staged = content
501 .encode_into(&mut self.payloads)
502 .and_then(|()| Span::at(offset, self.payloads.len() - offset))
503 .map(|span| Entry {
504 id: EntryId::new(),
505 parent,
506 timestamp_ms: now_ms(),
507 kind: content.kind(),
508 content: span,
509 })
510 .and_then(|entry| persist(&entry, &self.payloads[offset..]).map(|()| entry));
511 let entry = match staged {
512 Ok(entry) => entry,
513 Err(error) => {
514 self.payloads.truncate(offset);
515 return Err(error);
516 }
517 };
518 if entry.is_compaction() {
519 self.compaction_boundary = Some(entry.id);
520 }
521 let branch = self.active_branch_mut();
522 let idx = branch.append(entry);
523 Ok(&branch.entries[idx])
524 }
526 /// Append a compaction boundary entry after the selected entry and
527 /// select it. Returns the record so callers can persist it.
528 ///
529 /// # Errors
530 ///
531 /// As [`Session::append`].
532 pub fn append_compaction(&mut self, detail: serde_json::Value) -> Result<Entry> {
533 let content = EntryContent::Meta {
534 kind: COMPACTION_KIND.to_string(),
535 detail,
536 };
537 self.append(self.selected_id(), &content).copied()
538 }
540 /// The canonical CBOR content bytes of `entry`; empty when `entry` does
541 /// not belong to this session.
542 #[must_use]
543 pub fn bytes(&self, entry: &Entry) -> &[u8] {
544 self.payloads.get(entry.content.range()).unwrap_or_default()
545 }
547 /// Decode the content of `entry` into the caller's scope.
548 ///
549 /// # Errors
550 ///
551 /// Returns [`SmithError::Session`] when the bytes do not decode.
552 pub fn content(&self, entry: &Entry) -> Result<EntryContent> {
553 EntryContent::decode(self.bytes(entry))
270554 }
272556 /// The root-to-`at` entry chain, or `None` when `at` is unknown or its
293577 /// Entry IDs, order, and timestamps are preserved, `at` becomes the
294578 /// selected leaf, and the compaction boundary carries over when it lies
295579 /// on the retained path. The new session gets fresh session and branch
296 /// identity, because it is a different durable history.
580 /// identity, because it is a different durable history. The retained
581 /// records are copied with the one arena prefix their spans cover, so
582 /// spans stay valid unchanged.
297583 ///
298584 /// # Errors
299585 ///
306592 let boundary = self
307593 .compaction_boundary
308594 .filter(|id| entries.iter().any(|entry| entry.id == *id));
309 let selected_idx = entries.len().saturating_sub(1);
595 let end = entries
596 .iter()
597 .map(|entry| entry.content.end())
598 .max()
599 .unwrap_or(0);
310600 Ok(Self {
311601 id: SessionId::new(),
312602 branches: vec![Branch {
313603 branch_id: BranchId::new(),
314604 entries: entries.to_vec(),
315 selected_idx,
605 selected_idx: entries.len().saturating_sub(1),
316606 }],
607 payloads: self.payloads.get(..end).unwrap_or_default().to_vec(),
317608 active_branch_idx: 0,
318609 compaction_boundary: boundary,
319610 })
336627 /// its root-to-leaf chain is one branch. The last stored entry is the
337628 /// selected leaf of the active branch. Unknown frames are skipped here,
338629 /// and compaction entries restore the compaction boundary.
339 #[must_use]
340 pub fn from_frames(frames: &[crate::frame::Frame]) -> Self {
630 ///
631 /// Content bytes are copied into the arena, never decoded; every
632 /// collection is sized up front, so a linear history restores with a
633 /// constant number of allocations.
634 ///
635 /// # Errors
636 ///
637 /// Returns [`SmithError::Session`] when the content exceeds the arena cap.
638 pub fn from_frames(frames: &[Frame]) -> Result<Self> {
341639 let mut header = None;
342 let mut stored: Vec<Entry> = Vec::new();
343 let mut boundary = None;
640 let (mut count, mut total) = (0, 0);
344641 for frame in frames {
345642 match frame {
346 crate::frame::Frame::Header { header: found } => header = Some(*found),
347 crate::frame::Frame::Known { entry } => {
348 if entry.is_compaction() {
349 boundary = Some(entry.id);
350 }
351 stored.push(entry.clone());
643 Frame::Header { header: found } => header = Some(*found),
644 Frame::Known { entry } => {
645 count += 1;
646 total += entry.content.len();
352647 }
353 crate::frame::Frame::Unknown { .. } => {}
648 Frame::Unknown { .. } => {}
354649 }
355650 }
356 Self::from_entries(header, &stored, boundary)
651 Span::at(0, total)?;
652 let mut payloads = Vec::with_capacity(total);
653 let mut stored = Vec::with_capacity(count);
654 let mut boundary = None;
655 for frame in frames {
656 let Frame::Known { entry } = frame else {
657 continue;
658 };
659 let record = Entry {
660 id: entry.id,
661 parent: entry.parent,
662 timestamp_ms: entry.timestamp_ms,
663 kind: entry.kind,
664 content: Span::at(payloads.len(), entry.content.len())?,
665 };
666 payloads.extend_from_slice(&entry.content);
667 if record.is_compaction() {
668 boundary = Some(record.id);
669 }
670 stored.push(record);
671 }
672 let header = header.unwrap_or_else(|| SessionHeader {
673 session_id: SessionId::new(),
674 branch_id: BranchId::new(),
675 });
676 let (branches, active_branch_idx) = restore_branches(&stored, header.branch_id);
677 Ok(Self {
678 id: header.session_id,
679 branches,
680 payloads,
681 active_branch_idx,
682 compaction_boundary: boundary,
683 })
357684 }
685}
359 /// Rebuild branches from stored entries and their parent links.
360 fn from_entries(
361 header: Option<SessionHeader>,
362 stored: &[Entry],
363 boundary: Option<EntryId>,
364 ) -> Self {
365 let mut session = Self::new();
366 if let Some(header) = header {
367 session.id = header.session_id;
368 session.active_branch_mut().branch_id = header.branch_id;
369 }
370 session.compaction_boundary = boundary;
371 if stored.is_empty() {
372 return session;
373 }
374 let parents: HashSet<EntryId> = stored.iter().filter_map(|entry| entry.parent).collect();
375 let known: HashMap<EntryId, &Entry> =
376 stored.iter().map(|entry| (entry.id, entry)).collect();
377 let last_id = stored[stored.len() - 1].id;
378 let mut branches = Vec::new();
379 let mut active_branch_idx = 0;
380 for leaf in stored.iter().filter(|entry| !parents.contains(&entry.id)) {
381 let mut entries = Vec::new();
382 let mut cursor = Some(leaf.id);
383 // Walk to the root; a missing parent ends the recoverable chain.
384 while let Some(id) = cursor {
385 match known.get(&id) {
386 Some(entry) => {
387 entries.push((*entry).clone());
388 cursor = entry.parent;
389 }
390 None => break,
391 }
392 }
393 entries.reverse();
394 let selected_idx = entries.len().saturating_sub(1);
395 let is_active = leaf.id == last_id;
396 if is_active {
397 active_branch_idx = branches.len();
398 }
399 branches.push(Branch {
400 // The selected branch owns the persisted identity; sibling
401 // branches derive theirs from their leaf, which keeps every
402 // reload of the same file identical.
403 branch_id: if is_active {
404 session.active_branch().branch_id
405 } else {
406 BranchId::from_u128(leaf.id.as_u128())
407 },
408 entries,
409 selected_idx,
410 });
411 }
412 session.branches = branches;
413 session.active_branch_idx = active_branch_idx;
414 session
687/// Rebuild branches from stored records and their parent links, returning
688/// them with the index of the active branch.
689fn restore_branches(stored: &[Entry], active_id: BranchId) -> (Vec<Branch>, usize) {
690 let Some(last) = stored.last() else {
691 return (vec![Branch::with_id(active_id)], 0);
692 };
693 // Entry id to its index and whether any stored entry names it as parent.
694 let mut nodes: HashMap<EntryId, (usize, bool)> = HashMap::with_capacity(stored.len());
695 for (idx, entry) in stored.iter().enumerate() {
696 nodes.insert(entry.id, (idx, false));
415697 }
698 for parent in stored.iter().filter_map(|entry| entry.parent) {
699 if let Some(node) = nodes.get_mut(&parent) {
700 node.1 = true;
701 }
702 }
703 let nodes = &nodes;
704 let is_leaf = |entry: &&Entry| nodes.get(&entry.id).is_some_and(|node| !node.1);
705 // Root-ward walk; a missing parent ends the recoverable chain, and the
706 // step cap ends a corrupt cycle.
707 let chain = |leaf: &Entry| {
708 let mut cursor = Some(leaf.id);
709 std::iter::from_fn(move || {
710 let (idx, _) = nodes.get(&cursor?)?;
711 let entry = stored.get(*idx)?;
712 cursor = entry.parent;
713 Some(*entry)
714 })
715 .take(stored.len())
716 };
717 let mut branches = Vec::with_capacity(stored.iter().filter(is_leaf).count());
718 let mut active_branch_idx = 0;
719 for leaf in stored.iter().filter(is_leaf) {
720 let mut entries = Vec::with_capacity(chain(leaf).count());
721 entries.extend(chain(leaf));
722 entries.reverse();
723 let is_active = leaf.id == last.id;
724 if is_active {
725 active_branch_idx = branches.len();
726 }
727 branches.push(Branch {
728 // The selected branch owns the persisted identity; sibling
729 // branches derive theirs from their leaf, which keeps every
730 // reload of the same file identical.
731 branch_id: if is_active {
732 active_id
733 } else {
734 BranchId::from_u128(leaf.id.as_u128())
735 },
736 selected_idx: entries.len().saturating_sub(1),
737 entries,
738 });
739 }
740 (branches, active_branch_idx)
418743#[cfg(test)]
423748)]
424749mod tests {
425750 use super::*;
426 use crate::frame::Frame;
427 use smith::message::Role;
429 fn message(text: &str, parent: Option<EntryId>) -> Entry {
430 Entry::message(Message::with_text(Role::User, text), parent)
752 fn message(text: &str) -> EntryContent {
753 EntryContent::Message(Message::with_text(Role::User, text))
431754 }
433 fn text_of(entry: &Entry) -> String {
434 match &entry.content {
756 fn text_of(session: &Session, entry: &Entry) -> String {
757 match session.content(entry).unwrap() {
435758 EntryContent::Message(m) => format!("{}", m.blocks.len()),
436 EntryContent::Meta { kind, .. } => kind.clone(),
759 EntryContent::Meta { kind, .. } => kind,
437760 other => panic!("unexpected content {other:?}"),
438761 }
439762 }
441 fn frames(session: &Session) -> Vec<Frame> {
764 /// The frame of every record in `entries`, content copied from `session`.
765 fn frames_of(session: &Session, entries: &[Entry]) -> Vec<Frame> {
442766 let mut frames = vec![Frame::Header {
443767 header: session.header(),
444768 }];
445 frames.extend(
446 session
447 .active_branch()
448 .entries
449 .iter()
450 .map(|entry| Frame::Known {
451 entry: entry.clone(),
452 }),
453 );
769 frames.extend(entries.iter().map(|entry| Frame::Known {
770 entry: EntryFrame {
771 id: entry.id,
772 parent: entry.parent,
773 timestamp_ms: entry.timestamp_ms,
774 kind: entry.kind,
775 content: session.bytes(entry).to_vec(),
776 },
777 }));
454778 frames
455779 }
781 fn frames(session: &Session) -> Vec<Frame> {
782 frames_of(session, &session.active_branch().entries)
783 }
785 fn ids(branch: &Branch) -> Vec<EntryId> {
786 branch.entries.iter().map(|entry| entry.id).collect()
787 }
457789 #[test]
458790 fn sibling_entries_restore_as_separate_branches() {
459 let root = message("root", None);
460 let first = message("first", Some(root.id));
461 let second = message("second", Some(root.id));
462 let stored = vec![root.clone(), first.clone(), second.clone()];
463 let header = SessionHeader {
464 session_id: SessionId::new(),
465 branch_id: BranchId::new(),
466 };
467 let session = Session::from_entries(Some(header), &stored, None);
791 // Explicit parents record two children of one root.
792 let mut scratch = Session::new();
793 let root = *scratch.append(None, &message("root")).unwrap();
794 let first = *scratch.append(Some(root.id), &message("first")).unwrap();
795 let second = *scratch.append(Some(root.id), &message("second")).unwrap();
796 let stored = frames(&scratch);
797 let session = Session::from_frames(&stored).unwrap();
468798 assert_eq!(session.branches.len(), 2);
469799 // The last stored entry selects the active branch and keeps the
470800 // persisted branch identity.
471801 assert_eq!(session.selected_id(), Some(second.id));
472 assert_eq!(session.active_branch().branch_id, header.branch_id);
473 let ids: Vec<EntryId> = session
474 .active_branch()
475 .entries
476 .iter()
477 .map(|entry| entry.id)
478 .collect();
479 assert_eq!(ids, vec![root.id, second.id]);
480 let sibling = &session.branches[1 - session.active_branch_idx];
481802 assert_eq!(
482 sibling.entries.iter().map(|e| e.id).collect::<Vec<_>>(),
483 vec![root.id, first.id]
803 session.active_branch().branch_id,
804 scratch.header().branch_id
805 );
806 assert_eq!(ids(session.active_branch()), vec![root.id, second.id]);
807 let sibling = &session.branches[1 - session.active_branch_idx];
808 assert_eq!(ids(sibling), vec![root.id, first.id]);
809 // Shared-prefix records point at the same content bytes.
810 assert_eq!(
811 session.content(&sibling.entries[0]).unwrap(),
812 scratch.content(&root).unwrap()
484813 );
485814 // Reconstruction is identical on a second pass, sibling ids included.
486 let again = Session::from_entries(Some(header), &stored, None);
815 let again = Session::from_frames(&stored).unwrap();
487816 assert_eq!(again, session);
488817 }
819 #[test]
820 fn appended_content_decodes_from_the_arena_and_records_its_kind() {
821 let mut session = Session::new();
822 let content = EntryContent::ToolResult {
823 ok: false,
824 output: "boom".to_string(),
825 call_id: ToolCallId::new(),
826 };
827 let entry = *session.append(None, &content).unwrap();
828 assert_eq!(entry.kind, content.kind());
829 assert_eq!(session.content(&entry).unwrap(), content);
830 assert_eq!(session.bytes(&entry).len(), entry.content.len as usize);
831 // A record from elsewhere reads as empty bytes and fails to decode.
832 let foreign = Entry {
833 content: Span {
834 offset: 1 << 20,
835 len: 4,
836 },
837 ..entry
838 };
839 assert!(session.bytes(&foreign).is_empty());
840 assert_eq!(
841 session.content(&foreign).unwrap_err().code(),
842 "ENTRY_DECODE"
843 );
844 }
846 #[test]
847 fn failed_persist_leaves_the_session_unchanged() {
848 let mut session = Session::new();
849 session.append(None, &message("kept")).unwrap();
850 let before = session.clone();
851 let err = session
852 .append_with(
853 session.selected_id(),
854 &EntryContent::Meta {
855 kind: COMPACTION_KIND.to_string(),
856 detail: serde_json::json!({}),
857 },
858 |_, bytes| {
859 assert!(!bytes.is_empty());
860 Err(SmithError::Cancelled)
861 },
862 )
863 .unwrap_err();
864 assert_eq!(err.code(), "CANCELLED");
865 assert_eq!(session, before);
866 }
490868 #[test]
491869 fn fork_preserves_ids_order_leaf_and_compaction_boundary() {
492870 let mut session = Session::new();
493 let root = message("root", None);
494 session.append_to_active(root.clone());
495 let boundary = session.append_compaction(serde_json::json!({"summarized": 1}));
496 let after = message("after", Some(boundary.id));
497 session.append_to_active(after.clone());
871 let root = *session.append(None, &message("root")).unwrap();
872 let boundary = session
873 .append_compaction(serde_json::json!({"summarized": 1}))
874 .unwrap();
875 let after = *session
876 .append(Some(boundary.id), &message("after"))
877 .unwrap();
499879 let forked = session.fork_at(boundary.id).unwrap();
500880 assert_ne!(forked.id, session.id);
501 assert_eq!(
502 forked
503 .active_branch()
504 .entries
505 .iter()
506 .map(|entry| entry.id)
507 .collect::<Vec<_>>(),
508 vec![root.id, boundary.id]
509 );
881 assert_eq!(ids(forked.active_branch()), vec![root.id, boundary.id]);
510882 assert_eq!(forked.selected_id(), Some(boundary.id));
511883 assert_eq!(forked.compaction_boundary, Some(boundary.id));
512884 assert_eq!(
514886 .active_branch()
515887 .entries
516888 .iter()
517 .map(text_of)
889 .map(|entry| text_of(&forked, entry))
518890 .collect::<Vec<_>>(),
519891 vec!["1".to_string(), COMPACTION_KIND.to_string()]
520892 );
893 // The fork carries only the arena prefix its records cover.
894 assert_eq!(forked.bytes(&after), &[] as &[u8]);
522896 // Forking before the boundary drops it, because it is not retained.
523897 let earlier = session.fork_at(root.id).unwrap();
532906 #[test]
533907 fn tool_use_json_inside_messages_encodes_identically() {
534 let call_id = smith::id::ToolCallId::new();
908 let call_id = ToolCallId::new();
535909 let block = |input: serde_json::Value| {
536910 let mut message = Message::with_text(Role::Assistant, "call");
537 message.add_block(smith::message::ContentBlock::ToolUse {
911 message.add_block(ContentBlock::ToolUse {
538912 name: "write".to_string(),
539913 input,
540914 call_id,
541915 });
542916 message
543917 };
544 let mut first = Entry::message(
545 block(serde_json::json!({"path": "p", "content": "c"})),
546 None,
547 );
548 let mut second = Entry::message(
549 block(serde_json::json!({"content": "c", "path": "p"})),
550 None,
551 );
918 let first = block(serde_json::json!({"path": "p", "content": "c"}));
919 let mut second = block(serde_json::json!({"content": "c", "path": "p"}));
552920 // Only key order may differ, so encodings must match.
553921 second.id = first.id;
554922 second.timestamp_ms = first.timestamp_ms;
555 if let (EntryContent::Message(a), EntryContent::Message(b)) =
556 (&mut first.content, &mut second.content)
557 {
558 b.id = a.id;
559 b.timestamp_ms = a.timestamp_ms;
560 }
561 let encode = |entry: &Entry| {
562 Frame::Known {
563 entry: entry.clone(),
564 }
565 .encode(1 << 20)
566 .unwrap()
567 };
568 assert_eq!(encode(&first), encode(&second));
923 let mut session = Session::new();
924 let a = *session.append(None, &EntryContent::Message(first)).unwrap();
925 let b = *session
926 .append(None, &EntryContent::Message(second))
927 .unwrap();
928 assert_eq!(session.bytes(&a), session.bytes(&b));
569929 }
571931 #[test]
578938 #[test]
579939 fn fork_rejects_broken_ancestry_and_forks_sibling_branches() {
580940 // A stored chain whose root parent is missing restores, but cannot fork.
581 let orphan = message("orphan", Some(EntryId::new()));
582 let child = message("child", Some(orphan.id));
583 let broken = Session::from_entries(None, &[orphan, child.clone()], None);
941 let mut scratch = Session::new();
942 let orphan = *scratch
943 .append(Some(EntryId::new()), &message("orphan"))
944 .unwrap();
945 let child = *scratch.append(Some(orphan.id), &message("child")).unwrap();
946 let broken = Session::from_frames(&frames(&scratch)).unwrap();
584947 assert_eq!(broken.selected_id(), Some(child.id));
585948 let err = broken.fork_at(child.id).unwrap_err();
586949 assert_eq!(err.code(), "ENTRY_NOT_FOUND");
588951 // A leaf on an inactive sibling branch forks along its own chain.
589 let root = message("root", None);
590 let first = message("first", Some(root.id));
591 let second = message("second", Some(root.id));
592 let siblings = Session::from_entries(None, &[root.clone(), first.clone(), second], None);
952 let mut scratch = Session::new();
953 let root = *scratch.append(None, &message("root")).unwrap();
954 let first = *scratch.append(Some(root.id), &message("first")).unwrap();
955 scratch.append(Some(root.id), &message("second")).unwrap();
956 let siblings = Session::from_frames(&frames(&scratch)).unwrap();
593957 let forked = siblings.fork_at(first.id).unwrap();
594 let ids: Vec<EntryId> = forked
595 .active_branch()
596 .entries
597 .iter()
598 .map(|e| e.id)
599 .collect();
600 assert_eq!(ids, vec![root.id, first.id]);
958 assert_eq!(ids(forked.active_branch()), vec![root.id, first.id]);
959 assert_eq!(text_of(&forked, &forked.active_branch().entries[1]), "1");
960 }
962 #[test]
963 fn loading_copies_content_bytes_without_decoding_them() {
964 let mut scratch = Session::new();
965 let root = *scratch.append(None, &message("root")).unwrap();
966 let mut stored = frames(&scratch);
967 if let Frame::Known { entry } = &mut stored[1] {
968 entry.content = vec![0xFF, 0x00];
969 }
970 let restored = Session::from_frames(&stored).unwrap();
971 let record = restored.active_branch().entries[0];
972 assert_eq!(record.kind, root.kind);
973 assert_eq!(restored.bytes(&record), &[0xFF, 0x00]);
974 assert_eq!(
975 restored.content(&record).unwrap_err().code(),
976 "ENTRY_DECODE"
977 );
601978 }
603980 #[test]
604981 fn compaction_boundary_survives_a_frame_round_trip() {
605982 let mut session = Session::new();
606 session.append_to_active(message("root", None));
607 let boundary = session.append_compaction(serde_json::json!({}));
608 let restored = Session::from_frames(&frames(&session));
983 session.append(None, &message("root")).unwrap();
984 let boundary = session.append_compaction(serde_json::json!({})).unwrap();
985 let restored = Session::from_frames(&frames(&session)).unwrap();
609986 assert_eq!(restored.compaction_boundary, Some(boundary.id));
610987 assert_eq!(restored.id, session.id);
611988 assert_eq!(
612989 restored.active_branch().branch_id,
613990 session.header().branch_id
614991 );
992 assert_eq!(restored, session);
615993 }

smith-core/src/store.rs

Modified

+74 / −61 text lines

11//! Durable session storage: append-only writer, incremental bounded loader,
22//! and atomic repair publication.
4use crate::frame::{Frame, Recovery, read_frames, write_frame};
5use crate::session::Session;
4use crate::frame::{Frame, Recovery, encode_entry, read_frames, write_frame};
5use crate::session::{Entry, Session};
66use smith::config::Config;
77use smith::error::{Result, SmithError};
88use smith::id::EntryId;
133133 /// Returns a framing error for oversized frames, or an input/output error.
134134 pub fn append_frame(&mut self, frame: &Frame) -> Result<()> {
135135 let bytes = frame.encode(self.config.max_frame_bytes)?;
136 self.file.write_all(&bytes).map_err(io_err("STORE_WRITE"))?;
136 self.write(&bytes)
137 }
139 /// Append one session record as an entry frame, framing its arena
140 /// `content` bytes directly. Size limits apply as in
141 /// [`SessionWriter::append_frame`].
142 ///
143 /// # Errors
144 ///
145 /// Returns a framing error for oversized frames, or an input/output error.
146 pub fn append_entry(&mut self, entry: &Entry, content: &[u8]) -> Result<()> {
147 let bytes = encode_entry(entry, content, self.config.max_frame_bytes)?;
148 self.write(&bytes)
149 }
151 fn write(&mut self, bytes: &[u8]) -> Result<()> {
152 self.file.write_all(bytes).map_err(io_err("STORE_WRITE"))?;
137153 self.file.flush().map_err(io_err("STORE_WRITE"))?;
138154 Ok(())
139155 }
174190 .iter()
175191 .any(|frame| matches!(frame, Frame::Header { .. }));
176192 let session = if has_header {
177 Session::from_frames(&recovery.frames)
193 Session::from_frames(&recovery.frames)?
178194 } else if recovery.frames.is_empty() && recovery.damage.is_empty() {
179195 let session = Session::new();
180196 writer.append_frame(&Frame::Header {
223239 config.max_frame_bytes,
224240 )?;
225241 for entry in &session.active_branch().entries {
226 write_frame(
227 &mut out,
228 &Frame::Known {
229 entry: entry.clone(),
230 },
231 config.max_frame_bytes,
232 )?;
242 let bytes = encode_entry(entry, session.bytes(entry), config.max_frame_bytes)?;
243 out.write_all(&bytes).map_err(io_err("CREATE_WRITE"))?;
233244 }
234245 out.sync_all().map_err(io_err("CREATE_SYNC"))?;
235246 }
236247 std::fs::rename(&tmp, path).map_err(io_err("CREATE_PUBLISH"))?;
237248 let (writer, recovery) = SessionWriter::attach(path.to_path_buf(), config, lock)?;
238249 Ok(OpenSession {
239 session: Session::from_frames(&recovery.frames),
250 session: Session::from_frames(&recovery.frames)?,
240251 writer,
241252 recovery,
242253 })
328339)]
329340mod tests {
330341 use super::*;
331 use crate::session::{Entry, EntryContent, Session};
342 use crate::session::{EntryContent, EntryFrame, EntryKind, Session};
332343 use smith::message::{ContentBlock, Message, Role};
334345 fn tmp_path(name: &str) -> PathBuf {
337348 dir.join(name)
338349 }
340 fn entry(text: &str) -> Entry {
341 Entry::message(Message::with_text(Role::User, text), None)
351 fn message(text: &str) -> EntryContent {
352 EntryContent::Message(Message::with_text(Role::User, text))
353 }
355 fn entry(text: &str) -> EntryFrame {
356 EntryFrame::new(None, &message(text)).unwrap()
357 }
359 fn text(entry: &EntryFrame) -> Option<String> {
360 match EntryContent::decode(&entry.content).unwrap() {
361 EntryContent::Message(m) => match &m.blocks[0] {
362 ContentBlock::Text(t) => Some(t.clone()),
363 _ => None,
364 },
365 _ => None,
366 }
342367 }
344369 fn frame(text: &str) -> Frame {
348373 fn text_of(frame: &Frame) -> String {
349374 match frame {
350 Frame::Known { entry } => match &entry.content {
351 EntryContent::Message(m) => match &m.blocks[0] {
352 ContentBlock::Text(t) => t.clone(),
353 other => panic!("unexpected block {other:?}"),
354 },
355 other => panic!("unexpected content {other:?}"),
356 },
375 Frame::Known { entry } => text(entry).unwrap(),
357376 other => panic!("unexpected frame {other:?}"),
358377 }
359378 }
364383 let _ = std::fs::remove_file(&path);
365384 let cfg = Config::default_valid();
366385 let first = entry("one");
367 let second = Entry::message(Message::with_text(Role::User, "two"), Some(first.id));
386 let second = EntryFrame::new(Some(first.id), &message("two")).unwrap();
368387 {
369388 let mut w = SessionWriter::open(&path, cfg.clone()).unwrap();
370389 w.append_frame(&Frame::Known {
378397 }
379398 let frames = load_session(&path, cfg.max_frame_bytes).unwrap().frames;
380399 assert_eq!(frames.len(), 2);
381 let session = Session::from_frames(&frames);
400 let session = Session::from_frames(&frames).unwrap();
382401 assert_eq!(
383402 session
384403 .active_branch()
419438 let texts: Vec<String> = frames
420439 .iter()
421440 .filter_map(|f| match f {
422 Frame::Known { entry } => match &entry.content {
423 EntryContent::Message(m) => match &m.blocks[0] {
424 ContentBlock::Text(t) => Some(t.clone()),
425 _ => None,
426 },
427 _ => None,
428 },
441 Frame::Known { entry } => text(entry),
429442 _ => None,
430443 })
431444 .collect();
516529 {
517530 let mut w = SessionWriter::open(&path, cfg.clone()).unwrap();
518531 w.append_frame(&frame("small")).unwrap();
519 let big = Entry::message(
520 {
532 let big = EntryFrame::new(
533 None,
534 &EntryContent::Message({
521535 let mut m = Message::with_text(Role::User, "x");
522536 m.add_block(ContentBlock::text("y".repeat(8192)));
523537 m
524 },
525 None,
526 );
538 }),
539 )
540 .unwrap();
527541 let err = w.append_frame(&Frame::Known { entry: big }).unwrap_err();
528542 assert_eq!(err.code(), "FRAME_TOO_LARGE");
529543 }
613627 other => panic!("expected unknown frame, got {other:?}"),
614628 }
615629 match &frames[1] {
616 Frame::Known { entry } => match &entry.content {
617 EntryContent::Message(m) => match &m.blocks[0] {
618 ContentBlock::Text(t) => assert_eq!(t, "known"),
619 other => panic!("unexpected block {other:?}"),
620 },
621 other => panic!("unexpected content {other:?}"),
622 },
630 Frame::Known { entry } => assert_eq!(text(entry).as_deref(), Some("known")),
623631 other => panic!("expected known frame, got {other:?}"),
624632 }
625633 let _ = std::fs::remove_file(&path);
655663 .unwrap()
656664 .frames;
657665 assert_eq!(frames.len(), 5); // header + call/result x2
658 let restored = Session::from_frames(&frames);
666 let restored = Session::from_frames(&frames).unwrap();
659667 assert_eq!(restored.id, opened_id);
660668 assert_eq!(restored.active_branch().entries.len(), 4);
661669 // Tool call/result pairs stay adjacent and ordered.
663671 .active_branch()
664672 .entries
665673 .iter()
666 .map(|e| match &e.content {
667 EntryContent::ToolCall { .. } => "call",
668 EntryContent::ToolResult { .. } => "result",
674 .map(|e| match e.kind {
675 EntryKind::ToolCall { .. } => "call",
676 EntryKind::ToolResult { .. } => "result",
669677 _ => "other",
670678 })
671679 .collect();
726734 let (source_session, boundary_id, leaf_id) = {
727735 let mut opened = open_session(&source_path, cfg.clone()).unwrap();
728 let root = entry("root");
729 let root_id = root.id;
730 opened.session.append_to_active(root.clone());
736 let root = *opened.session.append(None, &message("root")).unwrap();
731737 opened
732738 .writer
733 .append_frame(&Frame::Known { entry: root })
739 .append_entry(&root, opened.session.bytes(&root))
734740 .unwrap();
735741 let boundary = opened
736742 .session
737 .append_compaction(serde_json::json!({"kept": 1}));
743 .append_compaction(serde_json::json!({"kept": 1}))
744 .unwrap();
738745 opened
739746 .writer
740 .append_frame(&Frame::Known {
741 entry: boundary.clone(),
742 })
747 .append_entry(&boundary, opened.session.bytes(&boundary))
748 .unwrap();
749 let tip = *opened
750 .session
751 .append(Some(boundary.id), &message("after"))
743752 .unwrap();
744 let tip = Entry::message(Message::with_text(Role::User, "after"), Some(boundary.id));
745 let tip_id = tip.id;
746 opened.session.append_to_active(tip.clone());
747753 opened
748754 .writer
749 .append_frame(&Frame::Known { entry: tip })
755 .append_entry(&tip, opened.session.bytes(&tip))
750756 .unwrap();
751 assert_ne!(root_id, tip_id);
752 (opened.session, boundary.id, tip_id)
757 assert_ne!(root.id, tip.id);
758 (opened.session, boundary.id, tip.id)
753759 };
755761 let fork_id = {
769775 assert_eq!(reopened.session.selected_id(), Some(boundary_id));
770776 assert_eq!(reopened.session.active_branch().entries.len(), 2);
771777 assert_eq!(reopened.session.compaction_boundary, Some(boundary_id));
778 // Published content bytes decode to what the source recorded.
779 let content = |session: &Session| {
780 session
781 .content(&session.active_branch().entries[0])
782 .unwrap()
783 };
784 assert_eq!(content(&reopened.session), content(&source_session));
772785 }
774787 // The source keeps its own identity, tip, and entry count.

smith-core/src/tools.rs

Modified

+39 / −38 text lines

11//! Tool registry, validation, built-in file effects, and the durable
22//! outcome boundary between successful effects and recorded session frames.
4use crate::frame::{Frame, canonical_json};
54use crate::session::{Entry, EntryContent, Session};
65use crate::store::SessionWriter;
76use smith::config::Config;
177176 self
178177 }
180 /// The durable writer, when this session persists.
181 pub const fn writer_mut(&mut self) -> Option<&mut SessionWriter> {
182 self.writer.as_mut()
183 }
185179 /// The registered tool definitions, for provider requests.
186180 #[must_use]
187181 pub fn registered_tools(&self) -> Vec<ToolMetadata> {
334328 if self.cancel.is_cancelled() && failure == EffectFailure::ReturnError {
335329 return Err(SmithError::Cancelled);
336330 }
337 let canonical_input = canonical_json(recorded_input);
338 let parent = self.session.selected_id();
339 self.record_entry(Entry::new(
340 parent,
341 EntryContent::ToolCall {
342 name: name.to_string(),
343 input: canonical_input,
344 call_id,
345 },
346 ))?;
331 self.record(&EntryContent::ToolCall {
332 name: name.to_string(),
333 input: recorded_input.clone(),
334 call_id,
335 })?;
347336 let effect = if self.cancel.is_cancelled() {
348337 Err(SmithError::Cancelled)
349338 } else {
368357 output: output.clone(),
369358 timestamp_ms: now_ms(),
370359 };
371 self.record_entry(Entry::new(
372 self.session.selected_id(),
373 EntryContent::ToolResult {
374 ok,
375 output,
376 call_id,
377 },
378 ))
360 self.record(&EntryContent::ToolResult {
361 ok,
362 output,
363 call_id,
364 })
379365 .map_err(|err| SmithError::RecordFailed {
380366 tool: name.to_string(),
381367 mutation_applied: ok && mutates_host(name),
388374 }
389375 }
391 fn record_entry(&mut self, entry: Entry) -> Result<()> {
392 if let Some(writer) = &mut self.writer {
393 writer.append_frame(&Frame::Known {
394 entry: entry.clone(),
395 })?;
396 }
397 self.session.append_to_active(entry);
398 Ok(())
377 /// Append `content` after the selected entry and durably record it
378 /// first; a failed write leaves the session unchanged.
379 pub(crate) fn record(&mut self, content: &EntryContent) -> Result<Entry> {
380 let parent = self.session.selected_id();
381 let writer = self.writer.as_mut();
382 self.session
383 .append_with(parent, content, |entry, bytes| {
384 writer.map_or(Ok(()), |writer| writer.append_entry(entry, bytes))
385 })
386 .copied()
399387 }
930918)]
931919mod tests {
932920 use super::*;
921 use crate::session::EntryKind;
933922 use std::path::PathBuf;
935924 fn workdir(tag: &str) -> PathBuf {
10501039 .active_branch()
10511040 .entries
10521041 .iter()
1053 .map(|e| match &e.content {
1054 EntryContent::ToolCall { .. } => "call",
1055 EntryContent::ToolResult { .. } => "result",
1042 .map(|e| match e.kind {
1043 EntryKind::ToolCall { .. } => "call",
1044 EntryKind::ToolResult { .. } => "result",
10561045 _ => "other",
10571046 })
10581047 .collect();
10801069 .active_branch()
10811070 .entries
10821071 .iter()
1083 .filter(|e| matches!(&e.content, EntryContent::ToolResult { ok: false, .. }))
1072 .filter(|e| matches!(e.kind, EntryKind::ToolResult { ok: false, .. }))
10841073 .count();
10851074 assert_eq!(failed, 2);
11491138 ..
11511140 ));
1141 // Only the durably recorded call is part of the live session.
1142 let kinds: Vec<EntryKind> = ts
1143 .session
1144 .active_branch()
1145 .entries
1146 .iter()
1147 .map(|e| e.kind)
1148 .collect();
1149 assert!(matches!(kinds.as_slice(), [EntryKind::ToolCall { .. }]));
11541152 #[test]
13331331 // Two entries: call + failed result, both recorded.
13341332 assert_eq!(ts.session.active_branch().entries.len(), 2);
13351333 let last = &ts.session.active_branch().entries[1];
1336 match &last.content {
1337 EntryContent::ToolResult { ok, .. } => assert!(!ok),
1334 match ts.session.content(last).unwrap() {
1335 EntryContent::ToolResult { ok, output, .. } => {
1336 assert!(!ok);
1337 assert!(output.contains("READ_ERROR"));
1338 }
13381339 other => panic!("unexpected {other:?}"),
13401341 let _ = std::fs::remove_dir_all(&dir);

smith-core/src/trace.rs

Modified

+30 / −26 text lines

11//! Replay evidence derived from durable session state.
22//!
33//! A trace is an ordered, provider-free reconstruction of what a session
4//! recorded. It is derived only from persisted values, so the same session
5//! file always produces the same trace, byte for byte.
4//! recorded. It is derived only from persisted entry records, never from
5//! decoded content, so the same session file always produces the same trace,
6//! byte for byte.
7use crate::session::{EntryContent, Session};
8use crate::session::{COMPACTION_KIND, EntryKind, Session};
89use smith::id::SessionId;
1011/// Replay-relevant trace record (durable replay evidence).
5657 event_ref: format!("branch:{}", branch.branch_id),
5758 }];
5859 for entry in &branch.entries {
59 let (kind, event_ref) = match &entry.content {
60 EntryContent::Message(message) => (
61 TraceKind::MessageStreamed,
62 format!("message:{}", message.id),
63 ),
64 EntryContent::ToolCall { call_id, name, .. } => {
65 (TraceKind::ToolCallEmitted, format!("call:{name}:{call_id}"))
60 let (kind, event_ref) = match entry.kind {
61 EntryKind::Message { id, .. } => (TraceKind::MessageStreamed, format!("message:{id}")),
62 EntryKind::ToolCall { call_id } => {
63 (TraceKind::ToolCallEmitted, format!("call:{call_id}"))
6664 }
67 EntryContent::ToolResult { call_id, ok, .. } => (
65 EntryKind::ToolResult { call_id, ok } => (
6866 TraceKind::ToolResultReceived,
69 format!("result:{call_id}:{}", if *ok { "ok" } else { "failed" }),
67 format!("result:{call_id}:{}", if ok { "ok" } else { "failed" }),
7068 ),
71 EntryContent::Meta { kind, .. } if entry.is_compaction() => {
72 (TraceKind::Compaction, format!("meta:{kind}:{}", entry.id))
73 }
74 EntryContent::Meta { kind, .. } => {
75 (TraceKind::EntryAdded, format!("meta:{kind}:{}", entry.id))
69 EntryKind::Meta { compaction: true } => (
70 TraceKind::Compaction,
71 format!("meta:{COMPACTION_KIND}:{}", entry.id),
72 ),
73 EntryKind::Meta { compaction: false } => {
74 (TraceKind::EntryAdded, format!("meta:{}", entry.id))
7675 }
7776 };
7877 trace.push(TraceRecord {
117116)]
118117mod tests {
119118 use super::*;
120 use crate::session::Entry;
119 use crate::session::EntryContent;
121120 use crate::store::{load_session, open_session};
122121 use crate::tools::ToolSession;
123122 use smith::config::Config;
130129 #[test]
131130 fn trace_reports_tool_activity_and_compaction_in_order() {
132131 let mut session = Session::new();
133 session.append_to_active(Entry::message(
134 Message::with_text(Role::User, "hello"),
135 None,
136 ));
132 session
133 .append(
134 None,
135 &EntryContent::Message(Message::with_text(Role::User, "hello")),
136 )
137 .unwrap();
137138 let mut tools = ToolSession::new(std::env::temp_dir());
138139 tools.session = session;
139140 tools
140141 .invoke("ls", &serde_json::json!({"path": "."}))
141142 .unwrap();
142 tools.session.append_compaction(serde_json::json!({}));
143 tools
144 .session
145 .append_compaction(serde_json::json!({}))
146 .unwrap();
144148 assert_eq!(
145149 kinds(&replay(&tools.session)),
183187 };
184188 let first = load_session(&path, cfg.max_frame_bytes).unwrap().frames;
185189 let second = load_session(&path, cfg.max_frame_bytes).unwrap().frames;
186 let left = encode(&Session::from_frames(&first));
187 let right = encode(&Session::from_frames(&second));
190 let left = encode(&Session::from_frames(&first).unwrap());
191 let right = encode(&Session::from_frames(&second).unwrap());
188192 assert_eq!(left, right);
189193 assert_eq!(
190 kinds(&replay(&Session::from_frames(&first))),
194 kinds(&replay(&Session::from_frames(&first).unwrap())),
191195 vec![
192196 TraceKind::ReplayStarted,
193197 TraceKind::SessionCreated,

smith-core/tests/alloc_bounds.rs

Modified

+81 / −22 text lines

22//! memory accounting). Bounds only tighten.
44use smith::message::{Message, Role};
5use smith_alloc::{Counting, Scope, enter, snapshot};
6use smith_core::session::{Entry, Session};
5use smith_alloc::{Counting, Scope, Stats, enter, snapshot};
6use smith_core::frame::Frame;
7use smith_core::session::{EntryContent, EntryFrame, Session};
8use std::sync::Mutex;
810#[global_allocator]
911static ALLOC: Counting = Counting;
11/// `fork_at` over 1000 entries: the branch list, the chain `Vec`, and two allocations per cloned
12/// text entry (`blocks` and its `String`) until payloads become bytes at rest.
13const FORK_AT_1000_ALLOCATIONS: u64 = 2002;
13/// Scope counters are process-wide; measurements must not overlap.
14static MEASURING: Mutex<()> = Mutex::new(());
16/// `fork_at` over 1000 entries: the branch list, the record `Vec`, and one
17/// arena slice. Content bytes are copied, never decoded.
18const FORK_AT_1000_ALLOCATIONS: u64 = 3;
20/// `from_frames` over 1000 decoded frames: arena, stored records, the
21/// parent-link table, the branch list, and one branch's records, each sized
22/// up front. Independent of entry count.
23const FROM_FRAMES_1000_ALLOCATIONS: u64 = 5;
1525fn linear_session(len: usize) -> Session {
1626 let mut session = Session::new();
1727 for turn in 0..len {
18 let entry = Entry::message(
19 Message::with_text(Role::User, format!("turn {turn}")),
20 session.selected_id(),
21 );
22 session.append_to_active(entry);
28 let content = EntryContent::Message(Message::with_text(Role::User, format!("turn {turn}")));
29 session.append(session.selected_id(), &content).unwrap();
2330 }
2431 session
27/// Allocations and bytes charged to [`Scope::Session`] by one `fork_at` of the leaf.
28fn fork_cost(session: &Session) -> (u64, u64) {
29 let leaf = session.selected_id().expect("non-empty session");
30 let before = snapshot(Scope::Session);
34/// Allocations and bytes charged to [`Scope::Session`] while `run` executes.
35fn session_cost<T>(run: impl FnOnce() -> T) -> ((u64, u64), T) {
36 let _serial = MEASURING
37 .lock()
38 .unwrap_or_else(std::sync::PoisonError::into_inner);
39 let before: Stats = snapshot(Scope::Session);
3140 let guard = enter(Scope::Session);
32 let fork = session.fork_at(leaf).expect("leaf is known");
41 let out = run();
3342 drop(guard);
3443 let after = snapshot(Scope::Session);
44 (
45 (
46 after.allocations - before.allocations,
47 after.bytes - before.bytes,
48 ),
49 out,
50 )
51}
53/// Cost of one `fork_at` of the leaf.
54fn fork_cost(session: &Session) -> (u64, u64) {
55 let leaf = session.selected_id().expect("non-empty session");
56 let (cost, fork) = session_cost(|| session.fork_at(leaf).expect("leaf is known"));
3557 assert_eq!(
3658 fork.active_branch().entries.len(),
3759 session.active_branch().entries.len()
3860 );
39 drop(fork);
40 (
41 after.allocations - before.allocations,
42 after.bytes - before.bytes,
43 )
61 let last = fork.active_branch().entries[fork.active_branch().entries.len() - 1];
62 assert_eq!(fork.bytes(&last), session.bytes(&last));
63 cost
64}
66/// Cost of restoring `session` from its decoded frames; frame decoding
67/// itself happens before the measured scope.
68fn from_frames_cost(session: &Session) -> (u64, u64) {
69 let mut frames = vec![Frame::Header {
70 header: session.header(),
71 }];
72 frames.extend(
73 session
74 .active_branch()
75 .entries
76 .iter()
77 .map(|entry| Frame::Known {
78 entry: EntryFrame {
79 id: entry.id,
80 parent: entry.parent,
81 timestamp_ms: entry.timestamp_ms,
82 kind: entry.kind,
83 content: session.bytes(entry).to_vec(),
84 },
85 }),
86 );
87 let (cost, restored) = session_cost(|| Session::from_frames(&frames).expect("frames restore"));
88 assert_eq!(&restored, session);
89 cost
4692#[test]
4894 let session = linear_session(1000);
4995 let first = fork_cost(&session);
5096 let second = fork_cost(&session);
51 assert!(
52 first.0 <= FORK_AT_1000_ALLOCATIONS,
97 assert_eq!(
98 first.0, FORK_AT_1000_ALLOCATIONS,
5399 "fork_at allocated {} times, bound is {FORK_AT_1000_ALLOCATIONS}",
54100 first.0
55101 );
56102 assert_eq!(first, second);
105#[test]
106fn from_frames_allocates_independently_of_entry_count() {
107 let small = from_frames_cost(&linear_session(100));
108 let large = from_frames_cost(&linear_session(1000));
109 assert_eq!(
110 large.0, FROM_FRAMES_1000_ALLOCATIONS,
111 "from_frames allocated {} times, bound is {FROM_FRAMES_1000_ALLOCATIONS}",
112 large.0
113 );
114 assert_eq!(small.0, large.0);
115 assert_eq!(large, from_frames_cost(&linear_session(1000)));
116}

smith-harness/tests/alloc_bounds.rs

Modified

+6 / −5 text lines

77#[global_allocator]
88static ALLOC: Counting = Counting;
10/// One mock text turn on a fresh session: request build, stream consumption,
11/// two recorded entries, one frame write each.
12const MOCK_TURN_ALLOCATIONS: u64 = 220;
10/// One mock text turn on a fresh session: request build (one decode of the
11/// user message), stream consumption, two recorded entries encoded once into
12/// the arena, one single-buffer frame write each.
13const MOCK_TURN_ALLOCATIONS: u64 = 208;
1415fn mock_turn(tag: &str) -> (u64, u64) {
1516 let dir = std::env::temp_dir().join(format!("smith_alloc_{tag}_{}", std::process::id()));
3637 let first = mock_turn("a");
3738 let second = mock_turn("b");
3839 assert_eq!(first, second);
39 assert!(
40 first.0 <= MOCK_TURN_ALLOCATIONS,
40 assert_eq!(
41 first.0, MOCK_TURN_ALLOCATIONS,
4142 "turn allocated {} times, bound is {MOCK_TURN_ALLOCATIONS}",
4243 first.0
4344 );

smith-harness/tests/http_effect.rs

Modified

+1 / −1 text lines

3333 .frames
3434 .into_iter()
3535 .filter_map(|frame| match frame {
36 Frame::Known { entry } => match entry.content {
36 Frame::Known { entry } => match EntryContent::decode(&entry.content).unwrap() {
3737 EntryContent::Meta { kind, detail } if kind == PROVIDER_HTTP_KIND => Some(detail),
3838 _ => None,
3939 },