repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

refactor(core): Session::append derives the parent from the selected leaf; stored parent links enter only through frames

68397e9cb53620577f804ea5bb91ce74b049d2e3

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (8)

+51 / −52 text lines

Diff layout

.system/plans/SMH-PLAN-82POBOKB-session-arena/index.md

Modified

+1 / −1 text lines

4848Session API:
50- `Session::append(&mut self, parent, content: &EntryContent) -> &Entry` encodes once into the arena.
50- `Session::append(&mut self, content: &EntryContent) -> Result<&Entry>` encodes once into the arena after the selected leaf; stored parent links outside that chain only enter through frames.
5151- `Session::content(&self, entry: &Entry) -> Result<EntryContent>` decodes on demand.
5252- `Session::bytes(&self, entry: &Entry) -> &[u8]` for writers and hashing.
5353- `Session::fork_at` copies the retained records and one arena slice.

smith-core/src/frame.rs

Modified

+1 / −1 text lines

@@ -598,7 +598,7 @@ entry_frame_carries_kind_and_content_as_one_byte_string
599599 // A session record frames straight from arena bytes, identically.
600600 let mut session = Session::new();
601 let record = *session.append(None, &content).unwrap();
601 let record = *session.append(&content).unwrap();
602602 let from_arena =
603603 encode_entry(&record, session.bytes(&record), DEFAULT_MAX_FRAME_BYTES).unwrap();
604604 let owned = Frame::Known {

smith-core/src/lib.rs

Modified

+1 / −1 text lines

4545 fn session_creates_and_appends() {
4646 let mut session = Session::new();
4747 let msg = Message::with_text(Role::User, "hello");
48 let entry = *session.append(None, &EntryContent::Message(msg)).unwrap();
48 let entry = *session.append(&EntryContent::Message(msg)).unwrap();
4949 assert_eq!(session.active_branch().entries(), vec![entry]);
5050 assert_eq!(session.selected_id(), Some(entry.id));
5151 }

smith-core/src/session.rs

Modified

+40 / −37 text lines

479479 ///
480480 /// Returns [`SmithError::Session`] when the content cannot be encoded or
481481 /// 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(()))
482 pub fn append(&mut self, content: &EntryContent) -> Result<&Entry> {
483 self.append_with(content, |_, _| Ok(()))
484484 }
486486 /// [`Session::append`], running `persist` on the new record and its
492492 /// unchanged then.
493493 pub fn append_with(
494494 &mut self,
495 parent: Option<EntryId>,
496495 content: &EntryContent,
497496 persist: impl FnOnce(&Entry, &[u8]) -> Result<()>,
498497 ) -> Result<&Entry> {
498 let parent = self.selected_id();
499499 let offset = self.payloads.len();
500500 let staged = content
501501 .encode_into(&mut self.payloads)
532532 kind: COMPACTION_KIND.to_string(),
533533 detail,
534534 };
535 self.append(self.selected_id(), &content).copied()
535 self.append(&content).copied()
536536 }
538538 /// The canonical CBOR content bytes of `entry`; empty when `entry` does
794794 frames_of(session, &session.active_branch().entries)
795795 }
797 /// Frames of entries built outside any session, under a fresh header;
798 /// the only way to store parent links a session would not append.
799 fn stored(entries: &[EntryFrame]) -> (SessionHeader, Vec<Frame>) {
800 let header = SessionHeader {
801 session_id: SessionId::new(),
802 branch_id: BranchId::new(),
803 };
804 let mut frames = vec![Frame::Header { header }];
805 frames.extend(entries.iter().cloned().map(|entry| Frame::Known { entry }));
806 (header, frames)
807 }
797809 fn ids(branch: &Branch) -> Vec<EntryId> {
798810 branch.entries.iter().map(|entry| entry.id).collect()
799811 }
801813 #[test]
802814 fn sibling_entries_restore_as_separate_branches() {
803 // Explicit parents record two children of one root.
804 let mut scratch = Session::new();
805 let root = *scratch.append(None, &message("root")).unwrap();
806 let first = *scratch.append(Some(root.id), &message("first")).unwrap();
807 let second = *scratch.append(Some(root.id), &message("second")).unwrap();
808 let stored = frames(&scratch);
815 // Stored parent links record two children of one root.
816 let root = EntryFrame::new(None, &message("root")).unwrap();
817 let first = EntryFrame::new(Some(root.id), &message("first")).unwrap();
818 let second = EntryFrame::new(Some(root.id), &message("second")).unwrap();
819 let (header, stored) = stored(&[root.clone(), first.clone(), second.clone()]);
809820 let session = Session::from_frames(&stored).unwrap();
810821 assert_eq!(session.branches.len(), 2);
811822 // The last stored entry selects the active branch and keeps the
812823 // persisted branch identity.
813824 assert_eq!(session.selected_id(), Some(second.id));
814 assert_eq!(session.active_branch().id, scratch.header().branch_id);
825 assert_eq!(session.active_branch().id, header.branch_id);
815826 assert_eq!(ids(session.active_branch()), vec![root.id, second.id]);
816827 let sibling = &session.branches[1 - session.active_branch_idx];
817828 assert_eq!(ids(sibling), vec![root.id, first.id]);
818829 // Shared-prefix records point at the same content bytes.
819830 assert_eq!(
820831 session.content(&sibling.entries[0]).unwrap(),
821 scratch.content(&root).unwrap()
832 EntryContent::decode(&root.content).unwrap()
822833 );
823834 // Reconstruction is identical on a second pass, sibling ids included.
824835 let again = Session::from_frames(&stored).unwrap();
833844 output: "boom".to_string(),
834845 call_id: ToolCallId::new(),
835846 };
836 let entry = *session.append(None, &content).unwrap();
847 let entry = *session.append(&content).unwrap();
837848 assert_eq!(entry.kind, content.kind());
838849 assert_eq!(session.content(&entry).unwrap(), content);
839850 assert_eq!(session.bytes(&entry).len(), entry.content.len as usize);
855866 #[test]
856867 fn failed_persist_leaves_the_session_unchanged() {
857868 let mut session = Session::new();
858 session.append(None, &message("kept")).unwrap();
869 session.append(&message("kept")).unwrap();
859870 let before = session.clone();
860871 let err = session
861872 .append_with(
862 session.selected_id(),
863873 &EntryContent::Meta {
864874 kind: COMPACTION_KIND.to_string(),
865875 detail: serde_json::json!({}),
877887 #[test]
878888 fn fork_preserves_ids_order_leaf_and_compaction_boundary() {
879889 let mut session = Session::new();
880 let root = *session.append(None, &message("root")).unwrap();
890 let root = *session.append(&message("root")).unwrap();
881891 let boundary = session
882892 .append_compaction(serde_json::json!({"summarized": 1}))
883893 .unwrap();
884 let after = *session
885 .append(Some(boundary.id), &message("after"))
886 .unwrap();
894 let after = *session.append(&message("after")).unwrap();
888896 let forked = session.fork_at(boundary.id).unwrap();
889897 assert_ne!(forked.id, session.id);
930938 second.id = first.id;
931939 second.timestamp_ms = first.timestamp_ms;
932940 let mut session = Session::new();
933 let a = *session.append(None, &EntryContent::Message(first)).unwrap();
934 let b = *session
935 .append(None, &EntryContent::Message(second))
936 .unwrap();
941 let a = *session.append(&EntryContent::Message(first)).unwrap();
942 let b = *session.append(&EntryContent::Message(second)).unwrap();
937943 assert_eq!(session.bytes(&a), session.bytes(&b));
938944 }
947953 #[test]
948954 fn fork_rejects_broken_ancestry_and_forks_sibling_branches() {
949955 // A stored chain whose root parent is missing restores, but cannot fork.
950 let mut scratch = Session::new();
951 let orphan = *scratch
952 .append(Some(EntryId::new()), &message("orphan"))
953 .unwrap();
954 let child = *scratch.append(Some(orphan.id), &message("child")).unwrap();
955 let broken = Session::from_frames(&frames(&scratch)).unwrap();
956 let orphan = EntryFrame::new(Some(EntryId::new()), &message("orphan")).unwrap();
957 let child = EntryFrame::new(Some(orphan.id), &message("child")).unwrap();
958 let broken = Session::from_frames(&stored(&[orphan, child.clone()]).1).unwrap();
956959 assert_eq!(broken.selected_id(), Some(child.id));
957960 let err = broken.fork_at(child.id).unwrap_err();
958961 assert_eq!(err.code(), "ENTRY_NOT_FOUND");
960963 // A leaf on an inactive sibling branch forks along its own chain.
961 let mut scratch = Session::new();
962 let root = *scratch.append(None, &message("root")).unwrap();
963 let first = *scratch.append(Some(root.id), &message("first")).unwrap();
964 scratch.append(Some(root.id), &message("second")).unwrap();
965 let siblings = Session::from_frames(&frames(&scratch)).unwrap();
964 let root = EntryFrame::new(None, &message("root")).unwrap();
965 let first = EntryFrame::new(Some(root.id), &message("first")).unwrap();
966 let second = EntryFrame::new(Some(root.id), &message("second")).unwrap();
967 let siblings =
968 Session::from_frames(&stored(&[root.clone(), first.clone(), second]).1).unwrap();
966969 let forked = siblings.fork_at(first.id).unwrap();
967970 assert_eq!(ids(forked.active_branch()), vec![root.id, first.id]);
968971 assert_eq!(text_of(&forked, &forked.active_branch().entries[1]), "1");
971974 #[test]
972975 fn loading_copies_content_bytes_without_decoding_them() {
973976 let mut scratch = Session::new();
974 let root = *scratch.append(None, &message("root")).unwrap();
977 let root = *scratch.append(&message("root")).unwrap();
975978 let mut stored = frames(&scratch);
976979 if let Frame::Known { entry } = &mut stored[1] {
977980 entry.content = vec![0xFF, 0x00];
989992 #[test]
990993 fn content_of_a_record_whose_kind_lies_is_a_kind_mismatch() {
991994 let mut scratch = Session::new();
992 scratch.append(None, &message("root")).unwrap();
995 scratch.append(&message("root")).unwrap();
993996 let mut stored = frames(&scratch);
994997 let lie = EntryKind::ToolCall {
995998 call_id: ToolCallId::new(),
10101013 #[test]
10111014 fn compaction_boundary_survives_a_frame_round_trip() {
10121015 let mut session = Session::new();
1013 session.append(None, &message("root")).unwrap();
1016 session.append(&message("root")).unwrap();
10141017 let boundary = session.append_compaction(serde_json::json!({})).unwrap();
10151018 let restored = Session::from_frames(&frames(&session)).unwrap();
10161019 assert_eq!(restored.compaction_boundary, Some(boundary.id));

smith-core/src/store.rs

Modified

+2 / −5 text lines

731731 let (source_session, boundary_id, leaf_id) = {
732732 let mut opened = open_session(&source_path, cfg.clone()).unwrap();
733 let root = *opened.session.append(None, &message("root")).unwrap();
733 let root = *opened.session.append(&message("root")).unwrap();
734734 opened
735735 .writer
736736 .append_entry(&root, opened.session.bytes(&root))
743743 .writer
744744 .append_entry(&boundary, opened.session.bytes(&boundary))
745745 .unwrap();
746 let tip = *opened
747 .session
748 .append(Some(boundary.id), &message("after"))
749 .unwrap();
746 let tip = *opened.session.append(&message("after")).unwrap();
750747 opened
751748 .writer
752749 .append_entry(&tip, opened.session.bytes(&tip))

smith-core/src/tools.rs

Modified

+1 / −2 text lines

394394 /// Append `content` after the selected entry and durably record it
395395 /// first; a failed write leaves the session unchanged.
396396 pub(crate) fn record(&mut self, content: &EntryContent) -> Result<Entry> {
397 let parent = self.session.selected_id();
398397 let writer = self.writer.as_mut();
399398 self.session
400 .append_with(parent, content, |entry, bytes| {
399 .append_with(content, |entry, bytes| {
401400 writer.map_or(Ok(()), |writer| writer.append_entry(entry, bytes))
402401 })
403402 .copied()

smith-core/src/trace.rs

Modified

+4 / −4 text lines

130130 fn trace_reports_tool_activity_and_compaction_in_order() {
131131 let mut session = Session::new();
132132 session
133 .append(
134 None,
135 &EntryContent::Message(Message::with_text(Role::User, "hello")),
136 )
133 .append(&EntryContent::Message(Message::with_text(
134 Role::User,
135 "hello",
136 )))
137137 .unwrap();
138138 let mut tools = ToolSession::new(std::env::temp_dir());
139139 tools.session = session;

smith-core/tests/alloc_bounds.rs

Modified

+1 / −1 text lines

2626 let mut session = Session::new();
2727 for turn in 0..len {
2828 let content = EntryContent::Message(Message::with_text(Role::User, format!("turn {turn}")));
29 session.append(session.selected_id(), &content).unwrap();
29 session.append(&content).unwrap();
3030 }
3131 session