1#![forbid(unsafe_code)]
14
15use crate::attest::AttestError;
16use crate::envelope::{verify_opened, OpenedEnvelope, OpenedError, RedactedEnvelope};
17use crate::message::{CausedBy, Message};
18use crate::protocol::{CausalProtocol, CausalViolation, VerificationResult};
19use crate::r4::Signer;
20use crate::sexpr::{Atom, SExpr};
21use crate::typed_addr::FieldId;
22use alloc::string::String;
23use alloc::vec;
24use alloc::vec::Vec;
25use core::fmt;
26use hashbrown::{HashMap, HashSet};
27
28#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
30#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
31pub struct ContentHash(pub String);
32
33#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
35#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
36pub struct ThreadId(pub String);
37
38#[derive(Debug, Clone)]
46pub struct HashIndex {
47 map: HashMap<ContentHash, (ThreadId, usize)>,
48}
49
50impl HashIndex {
51 pub fn new() -> Self {
53 Self {
54 map: HashMap::new(),
55 }
56 }
57
58 pub fn with_capacity(capacity: usize) -> Self {
60 Self {
61 map: HashMap::with_capacity(capacity),
62 }
63 }
64
65 pub fn insert(&mut self, hash: ContentHash, thread: ThreadId, index: usize) -> bool {
70 use hashbrown::hash_map::Entry;
71 match self.map.entry(hash) {
72 Entry::Vacant(e) => {
73 e.insert((thread, index));
74 true
75 }
76 Entry::Occupied(_) => false,
77 }
78 }
79
80 pub fn lookup(&self, hash: &ContentHash, thread: &ThreadId) -> Option<usize> {
85 self.map
86 .get(hash)
87 .and_then(|(t, idx)| if t == thread { Some(*idx) } else { None })
88 }
89
90 pub fn contains(&self, hash: &ContentHash, thread: &ThreadId) -> bool {
94 self.lookup(hash, thread).is_some()
95 }
96
97 pub fn rebuild<I>(&mut self, iter: I)
102 where
103 I: IntoIterator<Item = (ContentHash, ThreadId, usize)>,
104 {
105 self.map.clear();
106 for (hash, thread, index) in iter {
107 self.insert(hash, thread, index);
108 }
109 }
110
111 pub fn len(&self) -> usize {
113 self.map.len()
114 }
115
116 pub fn is_empty(&self) -> bool {
118 self.map.is_empty()
119 }
120}
121
122impl Default for HashIndex {
123 fn default() -> Self {
124 Self::new()
125 }
126}
127
128pub use crate::repeat::{MaterializedPositions, PositionContext, PositionMetadata};
131
132pub trait MessageStore {
133 fn materialized_positions(&self) -> Option<&MaterializedPositions> {
137 None
138 }
139
140 fn lookup(&self, hash: &ContentHash) -> Option<&Message>;
142
143 fn lookup_in_thread(&self, hash: &ContentHash, thread: &ThreadId) -> Option<&Message>;
145
146 fn contains(&self, hash: &ContentHash, thread: &ThreadId) -> bool;
148
149 fn append(&mut self, hash: ContentHash, thread: ThreadId, message: Message) -> bool;
152
153 fn frontier(&self, thread: &ThreadId) -> Vec<&ContentHash>;
156
157 fn causal_closure(&self, hash: &ContentHash, thread: &ThreadId) -> Vec<ContentHash>;
160
161 fn envelope_in_thread(
174 &self,
175 hash: &ContentHash,
176 thread: &ThreadId,
177 ) -> Option<&RedactedEnvelope> {
178 let _ = (hash, thread);
179 None
180 }
181
182 fn opened_in_thread(&self, hash: &ContentHash, thread: &ThreadId) -> Option<&OpenedEnvelope> {
197 let _ = (hash, thread);
198 None
199 }
200}
201
202#[derive(Debug, Clone)]
207pub struct ThreadedMessageStore {
208 threads: HashMap<ThreadId, Vec<(ContentHash, Message)>>,
210 index: HashIndex,
212 referenced: HashMap<ThreadId, HashSet<ContentHash>>,
214 envelopes: HashMap<ContentHash, RedactedEnvelope>,
219 opened: HashMap<ContentHash, OpenedEnvelope>,
225}
226
227impl ThreadedMessageStore {
228 pub fn new() -> Self {
230 Self {
231 threads: HashMap::new(),
232 index: HashIndex::new(),
233 referenced: HashMap::new(),
234 envelopes: HashMap::new(),
235 opened: HashMap::new(),
236 }
237 }
238
239 pub fn append_envelope(
251 &mut self,
252 envelope: RedactedEnvelope,
253 signer: &dyn Signer,
254 ) -> Result<bool, AttestError> {
255 envelope.verify(signer)?;
256 use hashbrown::hash_map::Entry;
257 match self
258 .envelopes
259 .entry(ContentHash(envelope.header.content_hash.clone()))
260 {
261 Entry::Vacant(e) => {
262 e.insert(envelope);
263 Ok(true)
264 }
265 Entry::Occupied(_) => Ok(false),
266 }
267 }
268
269 pub fn append_opened(
283 &mut self,
284 envelope: OpenedEnvelope,
285 signer: &dyn Signer,
286 ) -> Result<bool, OpenedError> {
287 verify_opened(&envelope, signer)?;
288 if envelope.thread().is_none() {
291 return Err(OpenedError::MissingField {
292 field: FieldId::Thread,
293 });
294 }
295 use hashbrown::hash_map::Entry;
296 match self.opened.entry(ContentHash(envelope.root.clone())) {
297 Entry::Vacant(e) => {
298 e.insert(envelope);
299 Ok(true)
300 }
301 Entry::Occupied(_) => Ok(false),
302 }
303 }
304}
305
306impl Default for ThreadedMessageStore {
307 fn default() -> Self {
308 Self::new()
309 }
310}
311
312impl MessageStore for ThreadedMessageStore {
313 fn lookup(&self, hash: &ContentHash) -> Option<&Message> {
314 let (thread, idx) = self.index.map.get(hash)?;
316 self.threads
317 .get(thread)
318 .and_then(|msgs| msgs.get(*idx).map(|(_, m)| m))
319 }
320
321 fn lookup_in_thread(&self, hash: &ContentHash, thread: &ThreadId) -> Option<&Message> {
322 let idx = self.index.lookup(hash, thread)?;
323 self.threads
324 .get(thread)
325 .and_then(|msgs| msgs.get(idx).map(|(_, m)| m))
326 }
327
328 fn contains(&self, hash: &ContentHash, thread: &ThreadId) -> bool {
329 self.index.contains(hash, thread)
330 }
331
332 fn append(&mut self, hash: ContentHash, thread: ThreadId, message: Message) -> bool {
333 let thread_msgs = self.threads.entry(thread.clone()).or_default();
334 let idx = thread_msgs.len();
335
336 if !self.index.insert(hash.clone(), thread.clone(), idx) {
337 return false; }
339
340 if let Some(cb) = message.caused_by() {
342 let refs = self.referenced.entry(thread.clone()).or_default();
343 match cb {
344 CausedBy::Begin => {}
345 CausedBy::Single(h) => {
346 refs.insert(ContentHash(h.clone()));
347 }
348 CausedBy::Multiple(hs) => {
349 for h in hs {
350 refs.insert(ContentHash(h.clone()));
351 }
352 }
353 }
354 }
355
356 thread_msgs.push((hash, message));
357 true
358 }
359
360 fn frontier(&self, thread: &ThreadId) -> Vec<&ContentHash> {
361 let Some(msgs) = self.threads.get(thread) else {
362 return Vec::new();
363 };
364 let empty = HashSet::new();
365 let refs = self.referenced.get(thread).unwrap_or(&empty);
366 msgs.iter()
367 .map(|(h, _)| h)
368 .filter(|h| !refs.contains(*h))
369 .collect()
370 }
371
372 fn causal_closure(&self, hash: &ContentHash, thread: &ThreadId) -> Vec<ContentHash> {
373 let mut result = Vec::new();
374 let mut visited = HashSet::new();
375 let mut stack = Vec::new();
376
377 if self.index.contains(hash, thread) {
378 stack.push(hash.clone());
379 }
380
381 while let Some(current) = stack.pop() {
382 if !visited.insert(current.clone()) {
383 continue;
384 }
385 result.push(current.clone());
386
387 if let Some(msg) = self.lookup_in_thread(¤t, thread) {
389 if let Some(cb) = msg.caused_by() {
390 match cb {
391 CausedBy::Begin => {}
392 CausedBy::Single(h) => {
393 let ch = ContentHash(h.clone());
394 if !visited.contains(&ch) {
395 stack.push(ch);
396 }
397 }
398 CausedBy::Multiple(hs) => {
399 for h in hs {
400 let ch = ContentHash(h.clone());
401 if !visited.contains(&ch) {
402 stack.push(ch);
403 }
404 }
405 }
406 }
407 }
408 }
409 }
410
411 result
412 }
413
414 fn envelope_in_thread(
415 &self,
416 hash: &ContentHash,
417 thread: &ThreadId,
418 ) -> Option<&RedactedEnvelope> {
419 self.envelopes
422 .get(hash)
423 .filter(|e| e.header.thread == thread.0)
424 }
425
426 fn opened_in_thread(&self, hash: &ContentHash, thread: &ThreadId) -> Option<&OpenedEnvelope> {
427 self.opened
430 .get(hash)
431 .filter(|e| e.thread() == Some(thread.0.as_str()))
432 }
433}
434
435#[derive(Debug, Clone, PartialEq, Eq)]
441#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
442pub enum ClosureError {
443 TargetNotFound,
445 IncompleteStore { missing_hashes: Vec<ContentHash> },
447}
448
449impl fmt::Display for ClosureError {
450 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
451 match self {
452 Self::TargetNotFound => write!(f, "target message not found in store"),
453 Self::IncompleteStore { missing_hashes } => {
454 write!(f, "incomplete store, missing hashes: ")?;
455 for (i, h) in missing_hashes.iter().enumerate() {
456 if i > 0 {
457 write!(f, ", ")?;
458 }
459 write!(f, "{}", h.0)?;
460 }
461 Ok(())
462 }
463 }
464 }
465}
466
467#[derive(Debug, Clone, PartialEq, Eq)]
469#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
470pub enum BundleVerificationError {
471 HashMismatch {
473 hash: ContentHash,
474 expected: ContentHash,
475 computed: ContentHash,
476 },
477 DanglingReference { caused_by: String },
479 CausalViolation(CausalViolation),
481}
482
483impl fmt::Display for BundleVerificationError {
484 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
485 match self {
486 Self::HashMismatch {
487 hash,
488 expected,
489 computed,
490 } => write!(
491 f,
492 "hash mismatch for {}: expected {}, computed {}",
493 hash.0, expected.0, computed.0
494 ),
495 Self::DanglingReference { caused_by } => {
496 write!(f, "dangling :caused-by reference: {caused_by}")
497 }
498 Self::CausalViolation(v) => write!(f, "causal violation: {v}"),
499 }
500 }
501}
502
503#[derive(Debug, Clone, PartialEq, Eq)]
505pub struct MergeResult {
506 pub added: usize,
508 pub deduplicated: usize,
510}
511
512#[derive(Debug, Clone, PartialEq, Eq)]
518#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
519pub struct CausalClosureBundle {
520 pub target: ContentHash,
522 pub thread: ThreadId,
524 pub messages: Vec<(ContentHash, Message)>,
527}
528
529impl CausalClosureBundle {
530 pub fn extract<S: MessageStore>(
536 target: &ContentHash,
537 thread: &ThreadId,
538 store: &S,
539 ) -> Result<Self, ClosureError> {
540 let target_msg = store
542 .lookup_in_thread(target, thread)
543 .ok_or(ClosureError::TargetNotFound)?;
544
545 let mut visited = HashSet::new();
547 let mut stack = vec![target.clone()];
548 let mut hash_to_msg: Vec<(ContentHash, Message)> = Vec::new();
549 let mut missing = Vec::new();
550
551 let _ = target_msg; while let Some(current) = stack.pop() {
555 if !visited.insert(current.clone()) {
556 continue;
557 }
558
559 let msg = match store.lookup_in_thread(¤t, thread) {
560 Some(m) => m,
561 None => {
562 missing.push(current);
563 continue;
564 }
565 };
566
567 hash_to_msg.push((current.clone(), msg.clone()));
568
569 if let Some(cb) = msg.caused_by() {
571 match cb {
572 CausedBy::Begin => {}
573 CausedBy::Single(h) => {
574 let ch = ContentHash(h.clone());
575 if !visited.contains(&ch) {
576 stack.push(ch);
577 }
578 }
579 CausedBy::Multiple(hs) => {
580 for h in hs {
581 let ch = ContentHash(h.clone());
582 if !visited.contains(&ch) {
583 stack.push(ch);
584 }
585 }
586 }
587 }
588 }
589 }
590
591 if !missing.is_empty() {
592 return Err(ClosureError::IncompleteStore {
593 missing_hashes: missing,
594 });
595 }
596
597 let hash_to_idx: HashMap<ContentHash, usize> = hash_to_msg
600 .iter()
601 .enumerate()
602 .map(|(i, (h, _))| (h.clone(), i))
603 .collect();
604
605 let n = hash_to_msg.len();
606 let mut in_degree: Vec<usize> = alloc::vec![0; n];
607 let mut successors_map: Vec<Vec<usize>> = (0..n).map(|_| Vec::new()).collect();
608
609 for (idx, (_, m)) in hash_to_msg.iter().enumerate() {
611 if let Some(cb) = m.caused_by() {
612 let pred_hashes: Vec<&str> = match cb {
613 CausedBy::Begin => vec![],
614 CausedBy::Single(p) => vec![p.as_str()],
615 CausedBy::Multiple(ps) => ps.iter().map(|p| p.as_str()).collect(),
616 };
617 for p in pred_hashes {
618 if let Some(&pred_idx) = hash_to_idx.get(&ContentHash(p.into())) {
619 successors_map[pred_idx].push(idx);
620 in_degree[idx] += 1;
621 }
622 }
623 }
624 }
625
626 let mut queue: Vec<usize> = (0..n).filter(|&i| in_degree[i] == 0).collect();
628 queue.sort_by(|&a, &b| hash_to_msg[a].0.cmp(&hash_to_msg[b].0));
630
631 let mut sorted_indices: Vec<usize> = Vec::with_capacity(n);
632
633 while let Some(node) = queue.pop() {
634 sorted_indices.push(node);
635 for &succ in &successors_map[node] {
636 in_degree[succ] -= 1;
637 if in_degree[succ] == 0 {
638 let pos = queue.partition_point(|&x| {
640 hash_to_msg[x].0.cmp(&hash_to_msg[succ].0) == core::cmp::Ordering::Greater
641 });
642 queue.insert(pos, succ);
643 }
644 }
645 }
646
647 let mut msg_slots: Vec<Option<(ContentHash, Message)>> =
649 hash_to_msg.into_iter().map(Some).collect();
650 let messages: Vec<(ContentHash, Message)> = sorted_indices
651 .into_iter()
652 .filter_map(|i| msg_slots[i].take())
653 .collect();
654
655 Ok(CausalClosureBundle {
656 target: target.clone(),
657 thread: thread.clone(),
658 messages,
659 })
660 }
661
662 pub fn verify_completeness(&self) -> Result<(), Vec<BundleVerificationError>> {
667 let known: HashSet<&str> = self.messages.iter().map(|(h, _)| h.0.as_str()).collect();
668 let mut errors = Vec::new();
669
670 for (_, msg) in &self.messages {
671 if let Some(cb) = msg.caused_by() {
672 let refs: Vec<&str> = match cb {
673 CausedBy::Begin => vec![],
674 CausedBy::Single(h) => vec![h.as_str()],
675 CausedBy::Multiple(hs) => hs.iter().map(|h| h.as_str()).collect(),
676 };
677 for r in refs {
678 if !known.contains(r) {
679 errors.push(BundleVerificationError::DanglingReference {
680 caused_by: r.into(),
681 });
682 }
683 }
684 }
685 }
686
687 if errors.is_empty() {
688 Ok(())
689 } else {
690 Err(errors)
691 }
692 }
693
694 pub fn verify_hashes<F>(&self, hasher: F) -> Result<(), Vec<BundleVerificationError>>
701 where
702 F: Fn(&Message) -> ContentHash,
703 {
704 let mut errors = Vec::new();
705
706 for (expected_hash, msg) in &self.messages {
707 let computed = hasher(msg);
708 if &computed != expected_hash {
709 errors.push(BundleVerificationError::HashMismatch {
710 hash: expected_hash.clone(),
711 expected: expected_hash.clone(),
712 computed,
713 });
714 }
715 }
716
717 if errors.is_empty() {
718 Ok(())
719 } else {
720 Err(errors)
721 }
722 }
723
724 pub fn verify_causal(
729 &self,
730 protocol: &CausalProtocol,
731 ) -> Result<(), Vec<BundleVerificationError>> {
732 let mut temp_store = ThreadedMessageStore::new();
734 for (hash, msg) in &self.messages {
735 temp_store.append(hash.clone(), self.thread.clone(), msg.clone());
736 }
737
738 let mut errors = Vec::new();
739 for (_, msg) in &self.messages {
740 let perf_name = msg.performative().map(|p| p.name()).unwrap_or("");
741
742 let result = crate::protocol::verify_causal(
743 perf_name,
744 msg.caused_by(),
745 &temp_store,
746 protocol,
747 &self.thread,
748 );
749
750 if let VerificationResult::Violation(v) = result {
751 errors.push(BundleVerificationError::CausalViolation(v));
752 }
753 }
754
755 if errors.is_empty() {
756 Ok(())
757 } else {
758 Err(errors)
759 }
760 }
761
762 pub fn verify_full<F>(
767 &self,
768 hasher: F,
769 protocol: &CausalProtocol,
770 ) -> Result<(), Vec<BundleVerificationError>>
771 where
772 F: Fn(&Message) -> ContentHash,
773 {
774 let mut all_errors = Vec::new();
775
776 if let Err(mut errs) = self.verify_completeness() {
777 all_errors.append(&mut errs);
778 }
779 if let Err(mut errs) = self.verify_hashes(hasher) {
780 all_errors.append(&mut errs);
781 }
782 if let Err(mut errs) = self.verify_causal(protocol) {
783 all_errors.append(&mut errs);
784 }
785
786 if all_errors.is_empty() {
787 Ok(())
788 } else {
789 Err(all_errors)
790 }
791 }
792
793 pub fn merge<S: MessageStore>(&self, store: &mut S) -> MergeResult {
798 let mut added = 0;
799 let mut deduplicated = 0;
800
801 for (hash, msg) in &self.messages {
802 if store.append(hash.clone(), self.thread.clone(), msg.clone()) {
803 added += 1;
804 } else {
805 deduplicated += 1;
806 }
807 }
808
809 MergeResult {
810 added,
811 deduplicated,
812 }
813 }
814
815 pub fn to_sexpr(&self) -> SExpr {
817 let mut inner = vec![
818 SExpr::Atom(Atom::Symbol("causal-closure".into())),
819 SExpr::Atom(Atom::Keyword("target".into())),
820 SExpr::Atom(Atom::Str(self.target.0.clone())),
821 SExpr::Atom(Atom::Keyword("thread".into())),
822 SExpr::Atom(Atom::Str(self.thread.0.clone())),
823 SExpr::Atom(Atom::Keyword("messages".into())),
824 ];
825
826 let msg_list: Vec<SExpr> = self
827 .messages
828 .iter()
829 .map(|(_, msg)| SExpr::from(msg))
830 .collect();
831
832 inner.push(SExpr::List(msg_list));
833
834 SExpr::List(vec![
835 SExpr::Atom(Atom::Symbol("meta".into())),
836 SExpr::List(inner),
837 ])
838 }
839
840 pub fn len(&self) -> usize {
842 self.messages.len()
843 }
844
845 pub fn is_empty(&self) -> bool {
847 self.messages.is_empty()
848 }
849
850 pub fn hashes(&self) -> Vec<&ContentHash> {
852 self.messages.iter().map(|(h, _)| h).collect()
853 }
854}
855
856#[cfg(test)]
857mod tests {
858 use super::*;
859 use alloc::string::ToString;
860 use alloc::vec;
861 use alloc::vec::Vec;
862
863 fn hash(s: &str) -> ContentHash {
864 ContentHash(s.to_string())
865 }
866
867 fn thread(s: &str) -> ThreadId {
868 ThreadId(s.to_string())
869 }
870
871 #[test]
874 fn insert_returns_true_for_new_entry() {
875 let mut idx = HashIndex::new();
876 assert!(idx.insert(hash("h1"), thread("t1"), 0));
877 }
878
879 #[test]
880 fn insert_returns_false_for_duplicate() {
881 let mut idx = HashIndex::new();
882 idx.insert(hash("h1"), thread("t1"), 0);
883 assert!(!idx.insert(hash("h1"), thread("t1"), 1));
884 }
885
886 #[test]
887 fn insert_duplicate_does_not_overwrite() {
888 let mut idx = HashIndex::new();
889 idx.insert(hash("h1"), thread("t1"), 0);
890 idx.insert(hash("h1"), thread("t2"), 99);
891 assert_eq!(idx.lookup(&hash("h1"), &thread("t1")), Some(0));
893 }
894
895 #[test]
896 fn insert_distinct_hashes_independent() {
897 let mut idx = HashIndex::new();
898 assert!(idx.insert(hash("h1"), thread("t1"), 0));
899 assert!(idx.insert(hash("h2"), thread("t1"), 1));
900 assert_eq!(idx.len(), 2);
901 }
902
903 #[test]
906 fn lookup_returns_index_for_matching_thread() {
907 let mut idx = HashIndex::new();
908 idx.insert(hash("h1"), thread("t1"), 42);
909 assert_eq!(idx.lookup(&hash("h1"), &thread("t1")), Some(42));
910 }
911
912 #[test]
913 fn lookup_returns_none_for_wrong_thread() {
914 let mut idx = HashIndex::new();
915 idx.insert(hash("h1"), thread("t1"), 42);
916 assert_eq!(idx.lookup(&hash("h1"), &thread("t2")), None);
917 }
918
919 #[test]
920 fn lookup_returns_none_for_absent_hash() {
921 let idx = HashIndex::new();
922 assert_eq!(idx.lookup(&hash("h1"), &thread("t1")), None);
923 }
924
925 #[test]
928 fn contains_true_for_matching_thread() {
929 let mut idx = HashIndex::new();
930 idx.insert(hash("h1"), thread("t1"), 0);
931 assert!(idx.contains(&hash("h1"), &thread("t1")));
932 }
933
934 #[test]
935 fn contains_false_for_wrong_thread() {
936 let mut idx = HashIndex::new();
937 idx.insert(hash("h1"), thread("t1"), 0);
938 assert!(!idx.contains(&hash("h1"), &thread("t2")));
939 }
940
941 #[test]
942 fn contains_false_for_absent_hash() {
943 let idx = HashIndex::new();
944 assert!(!idx.contains(&hash("nonexistent"), &thread("t1")));
945 }
946
947 #[test]
950 fn thread_isolation_across_multiple_threads() {
951 let mut idx = HashIndex::new();
952 idx.insert(hash("h1"), thread("t1"), 0);
953 idx.insert(hash("h2"), thread("t2"), 1);
954 idx.insert(hash("h3"), thread("t1"), 2);
955
956 assert_eq!(idx.lookup(&hash("h1"), &thread("t1")), Some(0));
958 assert_eq!(idx.lookup(&hash("h3"), &thread("t1")), Some(2));
959 assert_eq!(idx.lookup(&hash("h2"), &thread("t1")), None);
960
961 assert_eq!(idx.lookup(&hash("h2"), &thread("t2")), Some(1));
963 assert_eq!(idx.lookup(&hash("h1"), &thread("t2")), None);
964 assert_eq!(idx.lookup(&hash("h3"), &thread("t2")), None);
965 }
966
967 #[test]
970 fn rebuild_clears_and_repopulates() {
971 let mut idx = HashIndex::new();
972 idx.insert(hash("old"), thread("t1"), 0);
973
974 idx.rebuild(vec![
975 (hash("new1"), thread("t1"), 0),
976 (hash("new2"), thread("t2"), 1),
977 ]);
978
979 assert_eq!(idx.len(), 2);
980 assert_eq!(idx.lookup(&hash("old"), &thread("t1")), None);
981 assert_eq!(idx.lookup(&hash("new1"), &thread("t1")), Some(0));
982 assert_eq!(idx.lookup(&hash("new2"), &thread("t2")), Some(1));
983 }
984
985 #[test]
986 fn rebuild_skips_duplicates_first_wins() {
987 let mut idx = HashIndex::new();
988 idx.rebuild(vec![
989 (hash("h1"), thread("t1"), 0),
990 (hash("h1"), thread("t2"), 99),
991 ]);
992 assert_eq!(idx.len(), 1);
993 assert_eq!(idx.lookup(&hash("h1"), &thread("t1")), Some(0));
994 }
995
996 #[test]
997 fn rebuild_from_empty_iterator() {
998 let mut idx = HashIndex::new();
999 idx.insert(hash("h1"), thread("t1"), 0);
1000 idx.rebuild(Vec::<(ContentHash, ThreadId, usize)>::new());
1001 assert!(idx.is_empty());
1002 }
1003
1004 #[test]
1007 fn new_index_is_empty() {
1008 let idx = HashIndex::new();
1009 assert!(idx.is_empty());
1010 assert_eq!(idx.len(), 0);
1011 }
1012
1013 #[test]
1014 fn len_tracks_insertions() {
1015 let mut idx = HashIndex::new();
1016 idx.insert(hash("h1"), thread("t1"), 0);
1017 idx.insert(hash("h2"), thread("t1"), 1);
1018 assert_eq!(idx.len(), 2);
1019 assert!(!idx.is_empty());
1020 }
1021
1022 #[test]
1025 fn with_capacity_creates_empty_index() {
1026 let idx = HashIndex::with_capacity(100);
1027 assert!(idx.is_empty());
1028 }
1029
1030 #[test]
1033 fn default_creates_empty_index() {
1034 let idx = HashIndex::default();
1035 assert!(idx.is_empty());
1036 }
1037
1038 #[test]
1041 #[allow(clippy::needless_range_loop)]
1042 fn scale_10k_messages_10_threads() {
1043 let mut idx = HashIndex::new();
1044 let threads: Vec<ThreadId> = (0..10).map(|i| thread(&i.to_string())).collect();
1045
1046 for t in 0..10 {
1048 for m in 0..1000 {
1049 let h = hash(&alloc::format!("t{}-m{}", t, m));
1050 assert!(idx.insert(h, threads[t].clone(), m));
1051 }
1052 }
1053 assert_eq!(idx.len(), 10_000);
1054
1055 for t in 0..10 {
1057 for m in 0..1000 {
1058 let h = hash(&alloc::format!("t{}-m{}", t, m));
1059 assert_eq!(idx.lookup(&h, &threads[t]), Some(m));
1060 let other = &threads[(t + 1) % 10];
1062 assert_eq!(idx.lookup(&h, other), None);
1063 }
1064 }
1065
1066 let mut entries = Vec::with_capacity(10_000);
1068 for t in 0..10 {
1069 for m in 0..1000 {
1070 entries.push((
1071 hash(&alloc::format!("t{}-m{}", t, m)),
1072 threads[t].clone(),
1073 m,
1074 ));
1075 }
1076 }
1077 idx.rebuild(entries);
1078 assert_eq!(idx.len(), 10_000);
1079
1080 assert_eq!(idx.lookup(&hash("t5-m500"), &threads[5]), Some(500));
1082 assert_eq!(idx.lookup(&hash("t5-m500"), &threads[0]), None);
1083 }
1084
1085 use crate::message::{CausedBy, Performative};
1090 use crate::sexpr::{Atom, SExpr};
1091
1092 fn simple_msg(perf: &str, content: &str, caused_by: Option<CausedBy>) -> Message {
1094 Message::Simple {
1095 performative: Performative::Core(
1096 crate::message::CorePerformative::parse(perf)
1097 .unwrap_or(crate::message::CorePerformative::Tell),
1098 ),
1099 recipient: None,
1100 content: SExpr::Atom(Atom::Str(content.to_string())),
1101 params: Vec::new(),
1102 thread: None,
1103 sender: None,
1104 caused_by,
1105 }
1106 }
1107
1108 #[test]
1111 fn append_returns_true_for_new_message() {
1112 let mut store = ThreadedMessageStore::new();
1113 let msg = simple_msg("tell", "hello", Some(CausedBy::Begin));
1114 assert!(store.append(hash("h1"), thread("t1"), msg));
1115 }
1116
1117 #[test]
1118 fn append_returns_false_for_duplicate_hash() {
1119 let mut store = ThreadedMessageStore::new();
1120 let msg1 = simple_msg("tell", "hello", Some(CausedBy::Begin));
1121 let msg2 = simple_msg("tell", "hello again", Some(CausedBy::Begin));
1122 store.append(hash("h1"), thread("t1"), msg1);
1123 assert!(!store.append(hash("h1"), thread("t1"), msg2));
1124 }
1125
1126 #[test]
1127 fn append_duplicate_cross_thread_rejected() {
1128 let mut store = ThreadedMessageStore::new();
1129 let msg1 = simple_msg("tell", "hello", Some(CausedBy::Begin));
1130 let msg2 = simple_msg("tell", "hello", Some(CausedBy::Begin));
1131 store.append(hash("h1"), thread("t1"), msg1);
1132 assert!(!store.append(hash("h1"), thread("t2"), msg2));
1134 }
1135
1136 #[test]
1139 fn lookup_returns_message_across_threads() {
1140 let mut store = ThreadedMessageStore::new();
1141 let msg = simple_msg("tell", "hello", Some(CausedBy::Begin));
1142 store.append(hash("h1"), thread("t1"), msg);
1143 let found = store.lookup(&hash("h1"));
1144 assert!(found.is_some());
1145 assert_eq!(
1146 found.unwrap().performative(),
1147 Some(&Performative::Core(crate::message::CorePerformative::Tell))
1148 );
1149 }
1150
1151 #[test]
1152 fn lookup_returns_none_for_absent() {
1153 let store = ThreadedMessageStore::new();
1154 assert!(store.lookup(&hash("nonexistent")).is_none());
1155 }
1156
1157 #[test]
1160 fn lookup_in_thread_returns_message_for_correct_thread() {
1161 let mut store = ThreadedMessageStore::new();
1162 let msg = simple_msg("tell", "hello", Some(CausedBy::Begin));
1163 store.append(hash("h1"), thread("t1"), msg);
1164 assert!(store.lookup_in_thread(&hash("h1"), &thread("t1")).is_some());
1165 }
1166
1167 #[test]
1168 fn lookup_in_thread_returns_none_for_wrong_thread() {
1169 let mut store = ThreadedMessageStore::new();
1170 let msg = simple_msg("tell", "hello", Some(CausedBy::Begin));
1171 store.append(hash("h1"), thread("t1"), msg);
1172 assert!(store.lookup_in_thread(&hash("h1"), &thread("t2")).is_none());
1173 }
1174
1175 #[test]
1176 fn lookup_in_thread_returns_none_for_absent() {
1177 let store = ThreadedMessageStore::new();
1178 assert!(store.lookup_in_thread(&hash("h1"), &thread("t1")).is_none());
1179 }
1180
1181 #[test]
1184 fn contains_true_for_existing_in_thread() {
1185 let mut store = ThreadedMessageStore::new();
1186 let msg = simple_msg("tell", "hello", Some(CausedBy::Begin));
1187 store.append(hash("h1"), thread("t1"), msg);
1188 assert!(store.contains(&hash("h1"), &thread("t1")));
1189 }
1190
1191 #[test]
1192 fn store_contains_false_for_wrong_thread() {
1193 let mut store = ThreadedMessageStore::new();
1194 let msg = simple_msg("tell", "hello", Some(CausedBy::Begin));
1195 store.append(hash("h1"), thread("t1"), msg);
1196 assert!(!store.contains(&hash("h1"), &thread("t2")));
1197 }
1198
1199 #[test]
1200 fn contains_false_for_absent() {
1201 let store = ThreadedMessageStore::new();
1202 assert!(!store.contains(&hash("h1"), &thread("t1")));
1203 }
1204
1205 #[test]
1208 fn frontier_empty_thread_returns_empty() {
1209 let store = ThreadedMessageStore::new();
1210 assert!(store.frontier(&thread("t1")).is_empty());
1211 }
1212
1213 #[test]
1214 fn frontier_single_begin_message_is_frontier() {
1215 let mut store = ThreadedMessageStore::new();
1216 store.append(
1217 hash("h1"),
1218 thread("t1"),
1219 simple_msg("tell", "start", Some(CausedBy::Begin)),
1220 );
1221 let f = store.frontier(&thread("t1"));
1222 assert_eq!(f.len(), 1);
1223 assert_eq!(f[0], &hash("h1"));
1224 }
1225
1226 #[test]
1227 fn frontier_chain_only_leaf_is_frontier() {
1228 let mut store = ThreadedMessageStore::new();
1229 store.append(
1230 hash("h1"),
1231 thread("t1"),
1232 simple_msg("tell", "start", Some(CausedBy::Begin)),
1233 );
1234 store.append(
1235 hash("h2"),
1236 thread("t1"),
1237 simple_msg("reply", "ack", Some(CausedBy::Single("h1".into()))),
1238 );
1239 let f = store.frontier(&thread("t1"));
1240 assert_eq!(f.len(), 1);
1241 assert_eq!(f[0], &hash("h2"));
1242 }
1243
1244 #[test]
1245 fn frontier_branching_two_leaves() {
1246 let mut store = ThreadedMessageStore::new();
1247 store.append(
1248 hash("root"),
1249 thread("t1"),
1250 simple_msg("tell", "start", Some(CausedBy::Begin)),
1251 );
1252 store.append(
1253 hash("b1"),
1254 thread("t1"),
1255 simple_msg("reply", "branch1", Some(CausedBy::Single("root".into()))),
1256 );
1257 store.append(
1258 hash("b2"),
1259 thread("t1"),
1260 simple_msg("reply", "branch2", Some(CausedBy::Single("root".into()))),
1261 );
1262 let mut f: Vec<_> = store.frontier(&thread("t1")).into_iter().cloned().collect();
1263 f.sort();
1264 assert_eq!(f, vec![hash("b1"), hash("b2")]);
1265 }
1266
1267 #[test]
1268 fn frontier_fan_in_merge_removes_predecessors() {
1269 let mut store = ThreadedMessageStore::new();
1270 store.append(
1271 hash("root"),
1272 thread("t1"),
1273 simple_msg("tell", "start", Some(CausedBy::Begin)),
1274 );
1275 store.append(
1276 hash("b1"),
1277 thread("t1"),
1278 simple_msg("reply", "a", Some(CausedBy::Single("root".into()))),
1279 );
1280 store.append(
1281 hash("b2"),
1282 thread("t1"),
1283 simple_msg("reply", "b", Some(CausedBy::Single("root".into()))),
1284 );
1285 store.append(
1287 hash("merge"),
1288 thread("t1"),
1289 simple_msg(
1290 "ok",
1291 "done",
1292 Some(CausedBy::Multiple(vec!["b1".into(), "b2".into()])),
1293 ),
1294 );
1295 let f = store.frontier(&thread("t1"));
1296 assert_eq!(f.len(), 1);
1297 assert_eq!(f[0], &hash("merge"));
1298 }
1299
1300 #[test]
1301 fn frontier_separate_threads_independent() {
1302 let mut store = ThreadedMessageStore::new();
1303 store.append(
1304 hash("h1"),
1305 thread("t1"),
1306 simple_msg("tell", "a", Some(CausedBy::Begin)),
1307 );
1308 store.append(
1309 hash("h2"),
1310 thread("t2"),
1311 simple_msg("tell", "b", Some(CausedBy::Begin)),
1312 );
1313 assert_eq!(store.frontier(&thread("t1")).len(), 1);
1314 assert_eq!(store.frontier(&thread("t2")).len(), 1);
1315 }
1316
1317 #[test]
1320 fn causal_closure_begin_message_is_singleton() {
1321 let mut store = ThreadedMessageStore::new();
1322 store.append(
1323 hash("h1"),
1324 thread("t1"),
1325 simple_msg("tell", "start", Some(CausedBy::Begin)),
1326 );
1327 let cc = store.causal_closure(&hash("h1"), &thread("t1"));
1328 assert_eq!(cc.len(), 1);
1329 assert_eq!(cc[0], hash("h1"));
1330 }
1331
1332 #[test]
1333 fn causal_closure_chain_returns_all_ancestors() {
1334 let mut store = ThreadedMessageStore::new();
1335 store.append(
1336 hash("h1"),
1337 thread("t1"),
1338 simple_msg("tell", "start", Some(CausedBy::Begin)),
1339 );
1340 store.append(
1341 hash("h2"),
1342 thread("t1"),
1343 simple_msg("reply", "mid", Some(CausedBy::Single("h1".into()))),
1344 );
1345 store.append(
1346 hash("h3"),
1347 thread("t1"),
1348 simple_msg("ok", "end", Some(CausedBy::Single("h2".into()))),
1349 );
1350 let mut cc = store.causal_closure(&hash("h3"), &thread("t1"));
1351 cc.sort();
1352 assert_eq!(cc, vec![hash("h1"), hash("h2"), hash("h3")]);
1353 }
1354
1355 #[test]
1356 fn causal_closure_fan_in_includes_all_branches() {
1357 let mut store = ThreadedMessageStore::new();
1358 store.append(
1359 hash("root"),
1360 thread("t1"),
1361 simple_msg("tell", "start", Some(CausedBy::Begin)),
1362 );
1363 store.append(
1364 hash("b1"),
1365 thread("t1"),
1366 simple_msg("reply", "a", Some(CausedBy::Single("root".into()))),
1367 );
1368 store.append(
1369 hash("b2"),
1370 thread("t1"),
1371 simple_msg("reply", "b", Some(CausedBy::Single("root".into()))),
1372 );
1373 store.append(
1374 hash("merge"),
1375 thread("t1"),
1376 simple_msg(
1377 "ok",
1378 "done",
1379 Some(CausedBy::Multiple(vec!["b1".into(), "b2".into()])),
1380 ),
1381 );
1382 let mut cc = store.causal_closure(&hash("merge"), &thread("t1"));
1383 cc.sort();
1384 assert_eq!(
1385 cc,
1386 vec![hash("b1"), hash("b2"), hash("merge"), hash("root")]
1387 );
1388 }
1389
1390 #[test]
1391 fn causal_closure_absent_message_returns_empty() {
1392 let store = ThreadedMessageStore::new();
1393 let cc = store.causal_closure(&hash("nonexistent"), &thread("t1"));
1394 assert!(cc.is_empty());
1395 }
1396
1397 #[test]
1398 fn causal_closure_wrong_thread_returns_empty() {
1399 let mut store = ThreadedMessageStore::new();
1400 store.append(
1401 hash("h1"),
1402 thread("t1"),
1403 simple_msg("tell", "start", Some(CausedBy::Begin)),
1404 );
1405 let cc = store.causal_closure(&hash("h1"), &thread("t2"));
1406 assert!(cc.is_empty());
1407 }
1408
1409 #[test]
1410 fn causal_closure_diamond_no_duplicates() {
1411 let mut store = ThreadedMessageStore::new();
1413 store.append(
1414 hash("root"),
1415 thread("t1"),
1416 simple_msg("tell", "start", Some(CausedBy::Begin)),
1417 );
1418 store.append(
1419 hash("a"),
1420 thread("t1"),
1421 simple_msg("reply", "a", Some(CausedBy::Single("root".into()))),
1422 );
1423 store.append(
1424 hash("b"),
1425 thread("t1"),
1426 simple_msg("reply", "b", Some(CausedBy::Single("root".into()))),
1427 );
1428 store.append(
1429 hash("merge"),
1430 thread("t1"),
1431 simple_msg(
1432 "ok",
1433 "done",
1434 Some(CausedBy::Multiple(vec!["a".into(), "b".into()])),
1435 ),
1436 );
1437 let cc = store.causal_closure(&hash("merge"), &thread("t1"));
1438 assert_eq!(cc.len(), 4);
1440 let mut sorted = cc.clone();
1441 sorted.sort();
1442 sorted.dedup();
1443 assert_eq!(sorted.len(), 4);
1444 }
1445
1446 #[test]
1449 fn append_is_monotonic_store_only_grows() {
1450 let mut store = ThreadedMessageStore::new();
1451 store.append(
1452 hash("h1"),
1453 thread("t1"),
1454 simple_msg("tell", "a", Some(CausedBy::Begin)),
1455 );
1456 assert!(store.contains(&hash("h1"), &thread("t1")));
1457 store.append(
1458 hash("h2"),
1459 thread("t1"),
1460 simple_msg("reply", "b", Some(CausedBy::Single("h1".into()))),
1461 );
1462 assert!(store.contains(&hash("h1"), &thread("t1")));
1464 assert!(store.contains(&hash("h2"), &thread("t1")));
1465 }
1466
1467 #[test]
1470 fn message_without_caused_by_is_frontier() {
1471 let mut store = ThreadedMessageStore::new();
1472 let msg = Message::Simple {
1473 performative: Performative::Core(crate::message::CorePerformative::Tell),
1474 recipient: None,
1475 content: SExpr::Atom(Atom::Str("no causality".to_string())),
1476 params: Vec::new(),
1477 thread: None,
1478 sender: None,
1479 caused_by: None,
1480 };
1481 store.append(hash("h1"), thread("t1"), msg);
1482 let f = store.frontier(&thread("t1"));
1483 assert_eq!(f.len(), 1);
1484 assert_eq!(f[0], &hash("h1"));
1485 }
1486
1487 #[test]
1490 fn scale_1000_message_chain() {
1491 let mut store = ThreadedMessageStore::new();
1492 let t = thread("t1");
1493
1494 store.append(
1496 hash("m0"),
1497 t.clone(),
1498 simple_msg("tell", "start", Some(CausedBy::Begin)),
1499 );
1500 for i in 1..1000 {
1501 let h = hash(&alloc::format!("m{}", i));
1502 let prev = alloc::format!("m{}", i - 1);
1503 store.append(
1504 h,
1505 t.clone(),
1506 simple_msg("reply", "msg", Some(CausedBy::Single(prev))),
1507 );
1508 }
1509
1510 let f = store.frontier(&t);
1512 assert_eq!(f.len(), 1);
1513 assert_eq!(f[0], &hash("m999"));
1514
1515 let cc = store.causal_closure(&hash("m999"), &t);
1517 assert_eq!(cc.len(), 1000);
1518
1519 let cc0 = store.causal_closure(&hash("m0"), &t);
1521 assert_eq!(cc0.len(), 1);
1522 }
1523
1524 #[test]
1531 fn bundle_extract_single_begin_message() {
1532 let mut store = ThreadedMessageStore::new();
1533 let t = thread("t1");
1534 store.append(
1535 hash("h1"),
1536 t.clone(),
1537 simple_msg("tell", "start", Some(CausedBy::Begin)),
1538 );
1539
1540 let bundle = CausalClosureBundle::extract(&hash("h1"), &t, &store).unwrap();
1541 assert_eq!(bundle.target, hash("h1"));
1542 assert_eq!(bundle.thread, t);
1543 assert_eq!(bundle.len(), 1);
1544 assert_eq!(bundle.messages[0].0, hash("h1"));
1545 }
1546
1547 #[test]
1548 fn bundle_extract_chain_topological_order() {
1549 let mut store = ThreadedMessageStore::new();
1550 let t = thread("t1");
1551 store.append(
1552 hash("h1"),
1553 t.clone(),
1554 simple_msg("tell", "start", Some(CausedBy::Begin)),
1555 );
1556 store.append(
1557 hash("h2"),
1558 t.clone(),
1559 simple_msg("reply", "mid", Some(CausedBy::Single("h1".into()))),
1560 );
1561 store.append(
1562 hash("h3"),
1563 t.clone(),
1564 simple_msg("ok", "end", Some(CausedBy::Single("h2".into()))),
1565 );
1566
1567 let bundle = CausalClosureBundle::extract(&hash("h3"), &t, &store).unwrap();
1568 assert_eq!(bundle.len(), 3);
1569
1570 let hashes: Vec<&ContentHash> = bundle.hashes();
1572 let pos_h1 = hashes.iter().position(|h| **h == hash("h1")).unwrap();
1573 let pos_h2 = hashes.iter().position(|h| **h == hash("h2")).unwrap();
1574 let pos_h3 = hashes.iter().position(|h| **h == hash("h3")).unwrap();
1575 assert!(pos_h1 < pos_h2);
1576 assert!(pos_h2 < pos_h3);
1577 }
1578
1579 #[test]
1580 fn bundle_extract_diamond_dag() {
1581 let mut store = ThreadedMessageStore::new();
1582 let t = thread("t1");
1583 store.append(
1584 hash("root"),
1585 t.clone(),
1586 simple_msg("tell", "start", Some(CausedBy::Begin)),
1587 );
1588 store.append(
1589 hash("a"),
1590 t.clone(),
1591 simple_msg("reply", "a", Some(CausedBy::Single("root".into()))),
1592 );
1593 store.append(
1594 hash("b"),
1595 t.clone(),
1596 simple_msg("reply", "b", Some(CausedBy::Single("root".into()))),
1597 );
1598 store.append(
1599 hash("merge"),
1600 t.clone(),
1601 simple_msg(
1602 "ok",
1603 "done",
1604 Some(CausedBy::Multiple(vec!["a".into(), "b".into()])),
1605 ),
1606 );
1607
1608 let bundle = CausalClosureBundle::extract(&hash("merge"), &t, &store).unwrap();
1609 assert_eq!(bundle.len(), 4);
1610
1611 let hashes: Vec<&ContentHash> = bundle.hashes();
1613 let pos = |h: &str| hashes.iter().position(|x| **x == hash(h)).unwrap();
1614 assert!(pos("root") < pos("a"));
1615 assert!(pos("root") < pos("b"));
1616 assert!(pos("a") < pos("merge"));
1617 assert!(pos("b") < pos("merge"));
1618 }
1619
1620 #[test]
1621 fn bundle_extract_partial_closure() {
1622 let mut store = ThreadedMessageStore::new();
1624 let t = thread("t1");
1625 store.append(
1626 hash("h1"),
1627 t.clone(),
1628 simple_msg("tell", "start", Some(CausedBy::Begin)),
1629 );
1630 store.append(
1631 hash("h2"),
1632 t.clone(),
1633 simple_msg("reply", "mid", Some(CausedBy::Single("h1".into()))),
1634 );
1635 store.append(
1636 hash("h3"),
1637 t.clone(),
1638 simple_msg("ok", "end", Some(CausedBy::Single("h2".into()))),
1639 );
1640
1641 let bundle = CausalClosureBundle::extract(&hash("h2"), &t, &store).unwrap();
1642 assert_eq!(bundle.len(), 2);
1643 let mut sorted_hashes: Vec<ContentHash> = bundle.hashes().into_iter().cloned().collect();
1644 sorted_hashes.sort();
1645 assert_eq!(sorted_hashes, vec![hash("h1"), hash("h2")]);
1646 }
1647
1648 #[test]
1649 fn bundle_extract_target_not_found() {
1650 let store = ThreadedMessageStore::new();
1651 let result = CausalClosureBundle::extract(&hash("nonexistent"), &thread("t1"), &store);
1652 assert_eq!(result, Err(ClosureError::TargetNotFound));
1653 }
1654
1655 #[test]
1656 fn bundle_extract_wrong_thread() {
1657 let mut store = ThreadedMessageStore::new();
1658 store.append(
1659 hash("h1"),
1660 thread("t1"),
1661 simple_msg("tell", "start", Some(CausedBy::Begin)),
1662 );
1663 let result = CausalClosureBundle::extract(&hash("h1"), &thread("t2"), &store);
1664 assert_eq!(result, Err(ClosureError::TargetNotFound));
1665 }
1666
1667 #[test]
1670 fn bundle_verify_completeness_valid() {
1671 let mut store = ThreadedMessageStore::new();
1672 let t = thread("t1");
1673 store.append(
1674 hash("h1"),
1675 t.clone(),
1676 simple_msg("tell", "start", Some(CausedBy::Begin)),
1677 );
1678 store.append(
1679 hash("h2"),
1680 t.clone(),
1681 simple_msg("reply", "done", Some(CausedBy::Single("h1".into()))),
1682 );
1683
1684 let bundle = CausalClosureBundle::extract(&hash("h2"), &t, &store).unwrap();
1685 assert!(bundle.verify_completeness().is_ok());
1686 }
1687
1688 #[test]
1689 fn bundle_verify_completeness_dangling_reference() {
1690 let t = thread("t1");
1691 let bundle = CausalClosureBundle {
1693 target: hash("h2"),
1694 thread: t,
1695 messages: vec![(
1696 hash("h2"),
1697 simple_msg("reply", "done", Some(CausedBy::Single("missing".into()))),
1698 )],
1699 };
1700
1701 let result = bundle.verify_completeness();
1702 assert!(result.is_err());
1703 let errors = result.unwrap_err();
1704 assert_eq!(errors.len(), 1);
1705 assert!(
1706 matches!(&errors[0], BundleVerificationError::DanglingReference { caused_by } if caused_by == "missing")
1707 );
1708 }
1709
1710 #[test]
1713 fn bundle_verify_hashes_matching() {
1714 let mut store = ThreadedMessageStore::new();
1715 let t = thread("t1");
1716 store.append(
1717 hash("h1"),
1718 t.clone(),
1719 simple_msg("tell", "start", Some(CausedBy::Begin)),
1720 );
1721
1722 let bundle = CausalClosureBundle::extract(&hash("h1"), &t, &store).unwrap();
1723 let result = bundle.verify_hashes(|_| hash("h1"));
1725 assert!(result.is_ok());
1726 }
1727
1728 #[test]
1729 fn bundle_verify_hashes_mismatch() {
1730 let mut store = ThreadedMessageStore::new();
1731 let t = thread("t1");
1732 store.append(
1733 hash("h1"),
1734 t.clone(),
1735 simple_msg("tell", "start", Some(CausedBy::Begin)),
1736 );
1737
1738 let bundle = CausalClosureBundle::extract(&hash("h1"), &t, &store).unwrap();
1739 let result = bundle.verify_hashes(|_| hash("wrong"));
1741 assert!(result.is_err());
1742 let errors = result.unwrap_err();
1743 assert!(matches!(
1744 &errors[0],
1745 BundleVerificationError::HashMismatch { expected, computed, .. }
1746 if expected.0 == "h1" && computed.0 == "wrong"
1747 ));
1748 }
1749
1750 #[test]
1753 fn bundle_verify_causal_no_protocol_steps() {
1754 use crate::protocol::CausalProtocol;
1755 use alloc::collections::BTreeMap;
1756
1757 let mut store = ThreadedMessageStore::new();
1758 let t = thread("t1");
1759 store.append(
1760 hash("h1"),
1761 t.clone(),
1762 simple_msg("tell", "start", Some(CausedBy::Begin)),
1763 );
1764 store.append(
1765 hash("h2"),
1766 t.clone(),
1767 simple_msg("reply", "done", Some(CausedBy::Single("h1".into()))),
1768 );
1769
1770 let bundle = CausalClosureBundle::extract(&hash("h2"), &t, &store).unwrap();
1771 let empty_protocol = CausalProtocol {
1772 steps: BTreeMap::new(),
1773 };
1774 assert!(bundle.verify_causal(&empty_protocol).is_ok());
1775 }
1776
1777 #[test]
1780 fn bundle_merge_into_empty_store() {
1781 let mut source_store = ThreadedMessageStore::new();
1782 let t = thread("t1");
1783 source_store.append(
1784 hash("h1"),
1785 t.clone(),
1786 simple_msg("tell", "start", Some(CausedBy::Begin)),
1787 );
1788 source_store.append(
1789 hash("h2"),
1790 t.clone(),
1791 simple_msg("reply", "done", Some(CausedBy::Single("h1".into()))),
1792 );
1793
1794 let bundle = CausalClosureBundle::extract(&hash("h2"), &t, &source_store).unwrap();
1795
1796 let mut target_store = ThreadedMessageStore::new();
1797 let result = bundle.merge(&mut target_store);
1798 assert_eq!(result.added, 2);
1799 assert_eq!(result.deduplicated, 0);
1800
1801 assert!(target_store.contains(&hash("h1"), &t));
1803 assert!(target_store.contains(&hash("h2"), &t));
1804 }
1805
1806 #[test]
1807 fn bundle_merge_deduplication() {
1808 let mut store = ThreadedMessageStore::new();
1809 let t = thread("t1");
1810 store.append(
1811 hash("h1"),
1812 t.clone(),
1813 simple_msg("tell", "start", Some(CausedBy::Begin)),
1814 );
1815 store.append(
1816 hash("h2"),
1817 t.clone(),
1818 simple_msg("reply", "done", Some(CausedBy::Single("h1".into()))),
1819 );
1820
1821 let bundle = CausalClosureBundle::extract(&hash("h2"), &t, &store).unwrap();
1822
1823 let mut target_store = ThreadedMessageStore::new();
1825 target_store.append(
1826 hash("h1"),
1827 t.clone(),
1828 simple_msg("tell", "start", Some(CausedBy::Begin)),
1829 );
1830
1831 let result = bundle.merge(&mut target_store);
1832 assert_eq!(result.added, 1); assert_eq!(result.deduplicated, 1); }
1835
1836 #[test]
1837 fn bundle_merge_all_duplicates() {
1838 let mut store = ThreadedMessageStore::new();
1839 let t = thread("t1");
1840 store.append(
1841 hash("h1"),
1842 t.clone(),
1843 simple_msg("tell", "start", Some(CausedBy::Begin)),
1844 );
1845
1846 let bundle = CausalClosureBundle::extract(&hash("h1"), &t, &store).unwrap();
1847
1848 let result = bundle.merge(&mut store);
1850 assert_eq!(result.added, 0);
1851 assert_eq!(result.deduplicated, 1);
1852 }
1853
1854 #[test]
1857 fn bundle_to_sexpr_structure() {
1858 let mut store = ThreadedMessageStore::new();
1859 let t = thread("t1");
1860 store.append(
1861 hash("h1"),
1862 t.clone(),
1863 simple_msg("tell", "start", Some(CausedBy::Begin)),
1864 );
1865
1866 let bundle = CausalClosureBundle::extract(&hash("h1"), &t, &store).unwrap();
1867 let sexpr = bundle.to_sexpr();
1868
1869 if let SExpr::List(outer) = &sexpr {
1871 assert_eq!(outer.len(), 2);
1872 assert_eq!(outer[0], SExpr::Atom(Atom::Symbol("meta".into())));
1873 if let SExpr::List(inner) = &outer[1] {
1874 assert_eq!(inner[0], SExpr::Atom(Atom::Symbol("causal-closure".into())));
1875 assert_eq!(inner[1], SExpr::Atom(Atom::Keyword("target".into())));
1876 assert_eq!(inner[2], SExpr::Atom(Atom::Str("h1".into())));
1877 assert_eq!(inner[3], SExpr::Atom(Atom::Keyword("thread".into())));
1878 assert_eq!(inner[4], SExpr::Atom(Atom::Str("t1".into())));
1879 assert_eq!(inner[5], SExpr::Atom(Atom::Keyword("messages".into())));
1880 if let SExpr::List(msgs) = &inner[6] {
1881 assert_eq!(msgs.len(), 1); } else {
1883 panic!("expected messages list");
1884 }
1885 } else {
1886 panic!("expected inner list");
1887 }
1888 } else {
1889 panic!("expected outer list");
1890 }
1891 }
1892
1893 #[test]
1896 fn bundle_round_trip_extract_merge_matches() {
1897 let mut store = ThreadedMessageStore::new();
1898 let t = thread("t1");
1899 store.append(
1900 hash("h1"),
1901 t.clone(),
1902 simple_msg("tell", "start", Some(CausedBy::Begin)),
1903 );
1904 store.append(
1905 hash("h2"),
1906 t.clone(),
1907 simple_msg("reply", "mid", Some(CausedBy::Single("h1".into()))),
1908 );
1909 store.append(
1910 hash("h3"),
1911 t.clone(),
1912 simple_msg("ok", "end", Some(CausedBy::Single("h2".into()))),
1913 );
1914
1915 let bundle = CausalClosureBundle::extract(&hash("h3"), &t, &store).unwrap();
1916 assert!(bundle.verify_completeness().is_ok());
1917
1918 let mut target = ThreadedMessageStore::new();
1920 let result = bundle.merge(&mut target);
1921 assert_eq!(result.added, 3);
1922
1923 let cc = target.causal_closure(&hash("h3"), &t);
1925 assert_eq!(cc.len(), 3);
1926 }
1927
1928 #[test]
1929 fn bundle_round_trip_diamond() {
1930 let mut store = ThreadedMessageStore::new();
1931 let t = thread("t1");
1932 store.append(
1933 hash("root"),
1934 t.clone(),
1935 simple_msg("tell", "start", Some(CausedBy::Begin)),
1936 );
1937 store.append(
1938 hash("a"),
1939 t.clone(),
1940 simple_msg("reply", "a", Some(CausedBy::Single("root".into()))),
1941 );
1942 store.append(
1943 hash("b"),
1944 t.clone(),
1945 simple_msg("reply", "b", Some(CausedBy::Single("root".into()))),
1946 );
1947 store.append(
1948 hash("merge"),
1949 t.clone(),
1950 simple_msg(
1951 "ok",
1952 "done",
1953 Some(CausedBy::Multiple(vec!["a".into(), "b".into()])),
1954 ),
1955 );
1956
1957 let bundle = CausalClosureBundle::extract(&hash("merge"), &t, &store).unwrap();
1958 assert!(bundle.verify_completeness().is_ok());
1959
1960 let mut target = ThreadedMessageStore::new();
1961 let result = bundle.merge(&mut target);
1962 assert_eq!(result.added, 4);
1963
1964 let mut cc = target.causal_closure(&hash("merge"), &t);
1966 cc.sort();
1967 assert_eq!(cc, vec![hash("a"), hash("b"), hash("merge"), hash("root")]);
1968
1969 let f = target.frontier(&t);
1971 assert_eq!(f.len(), 1);
1972 assert_eq!(f[0], &hash("merge"));
1973 }
1974
1975 #[test]
1978 fn tier2_partial_closure_sufficient_for_target() {
1979 let mut store = ThreadedMessageStore::new();
1982 let t = thread("t1");
1983 store.append(
1984 hash("h1"),
1985 t.clone(),
1986 simple_msg("tell", "start", Some(CausedBy::Begin)),
1987 );
1988 store.append(
1989 hash("h2"),
1990 t.clone(),
1991 simple_msg("reply", "a", Some(CausedBy::Single("h1".into()))),
1992 );
1993 store.append(
1994 hash("h3"),
1995 t.clone(),
1996 simple_msg("reply", "b", Some(CausedBy::Single("h2".into()))),
1997 );
1998 store.append(
2000 hash("h4"),
2001 t.clone(),
2002 simple_msg("reply", "c", Some(CausedBy::Single("h1".into()))),
2003 );
2004
2005 let bundle = CausalClosureBundle::extract(&hash("h3"), &t, &store).unwrap();
2007 assert_eq!(bundle.len(), 3);
2008 let hashes: Vec<ContentHash> = bundle.hashes().into_iter().cloned().collect();
2009 assert!(hashes.contains(&hash("h1")));
2010 assert!(hashes.contains(&hash("h2")));
2011 assert!(hashes.contains(&hash("h3")));
2012 assert!(!hashes.contains(&hash("h4"))); assert!(bundle.verify_completeness().is_ok());
2014 }
2015
2016 #[test]
2019 fn tier3_full_audit_detects_hash_mismatch() {
2020 let t = thread("t1");
2021 let bundle = CausalClosureBundle {
2023 target: hash("h2"),
2024 thread: t,
2025 messages: vec![
2026 (
2027 hash("h1"),
2028 simple_msg("tell", "start", Some(CausedBy::Begin)),
2029 ),
2030 (
2031 hash("h2"),
2032 simple_msg("reply", "done", Some(CausedBy::Single("h1".into()))),
2033 ),
2034 ],
2035 };
2036
2037 let result = bundle.verify_hashes(|_| hash("computed-hash"));
2039 assert!(result.is_err());
2040 assert_eq!(result.unwrap_err().len(), 2);
2041 }
2042
2043 #[test]
2044 fn tier3_full_audit_detects_dangling_refs() {
2045 let t = thread("t1");
2046 let bundle = CausalClosureBundle {
2047 target: hash("h2"),
2048 thread: t,
2049 messages: vec![(
2050 hash("h2"),
2051 simple_msg("reply", "done", Some(CausedBy::Single("missing".into()))),
2052 )],
2053 };
2054
2055 let result = bundle.verify_completeness();
2056 assert!(result.is_err());
2057 }
2058
2059 #[test]
2060 fn tier3_full_audit_all_checks_pass() {
2061 let mut store = ThreadedMessageStore::new();
2062 let t = thread("t1");
2063 store.append(
2064 hash("h1"),
2065 t.clone(),
2066 simple_msg("tell", "start", Some(CausedBy::Begin)),
2067 );
2068 store.append(
2069 hash("h2"),
2070 t.clone(),
2071 simple_msg("reply", "mid", Some(CausedBy::Single("h1".into()))),
2072 );
2073 store.append(
2074 hash("h3"),
2075 t.clone(),
2076 simple_msg("ok", "end", Some(CausedBy::Single("h2".into()))),
2077 );
2078
2079 let bundle = CausalClosureBundle::extract(&hash("h3"), &t, &store).unwrap();
2080
2081 let result = bundle.verify_full(
2083 |msg| {
2084 match msg.caused_by() {
2086 Some(CausedBy::Begin) => hash("h1"),
2087 Some(CausedBy::Single(p)) if p == "h1" => hash("h2"),
2088 Some(CausedBy::Single(p)) if p == "h2" => hash("h3"),
2089 _ => hash("unknown"),
2090 }
2091 },
2092 &CausalProtocol {
2093 steps: alloc::collections::BTreeMap::new(),
2094 },
2095 );
2096 assert!(result.is_ok());
2097 }
2098
2099 #[test]
2102 fn bundle_empty_has_correct_len() {
2103 let bundle = CausalClosureBundle {
2104 target: hash("h1"),
2105 thread: thread("t1"),
2106 messages: vec![],
2107 };
2108 assert!(bundle.is_empty());
2109 assert_eq!(bundle.len(), 0);
2110 }
2111
2112 #[test]
2115 fn bundle_extract_100_message_chain() {
2116 let mut store = ThreadedMessageStore::new();
2117 let t = thread("t1");
2118
2119 store.append(
2120 hash("m0"),
2121 t.clone(),
2122 simple_msg("tell", "start", Some(CausedBy::Begin)),
2123 );
2124 for i in 1..100 {
2125 let h = hash(&alloc::format!("m{}", i));
2126 let prev = alloc::format!("m{}", i - 1);
2127 store.append(
2128 h,
2129 t.clone(),
2130 simple_msg("reply", "msg", Some(CausedBy::Single(prev))),
2131 );
2132 }
2133
2134 let bundle = CausalClosureBundle::extract(&hash("m99"), &t, &store).unwrap();
2135 assert_eq!(bundle.len(), 100);
2136 assert!(bundle.verify_completeness().is_ok());
2137
2138 let hashes: Vec<&ContentHash> = bundle.hashes();
2140 for i in 0..99 {
2141 let pos_i = hashes
2142 .iter()
2143 .position(|h| **h == hash(&alloc::format!("m{}", i)))
2144 .unwrap();
2145 let pos_next = hashes
2146 .iter()
2147 .position(|h| **h == hash(&alloc::format!("m{}", i + 1)))
2148 .unwrap();
2149 assert!(pos_i < pos_next, "m{} should come before m{}", i, i + 1);
2150 }
2151
2152 let mut target = ThreadedMessageStore::new();
2154 let result = bundle.merge(&mut target);
2155 assert_eq!(result.added, 100);
2156 assert_eq!(result.deduplicated, 0);
2157 }
2158
2159 use crate::attest::{sign_attestation_v2, AttestationHeader};
2164 use crate::keyid::KeyId;
2165 use alloc::collections::BTreeSet;
2166
2167 struct TestSigner {
2170 secret: &'static [u8],
2171 }
2172
2173 impl Signer for TestSigner {
2174 fn sign(&self, data: &[u8]) -> Vec<u8> {
2175 use sha2::{Digest, Sha256};
2176 let mut h = Sha256::new();
2177 h.update(self.secret);
2178 h.update(data);
2179 h.finalize().to_vec()
2180 }
2181 fn verify(&self, data: &[u8], sig: &[u8]) -> bool {
2182 self.sign(data) == sig
2183 }
2184 }
2185
2186 const SIGNER: TestSigner = TestSigner { secret: b"alice" };
2187
2188 fn env(hash_s: &str, perf: &str, thread_name: &str) -> RedactedEnvelope {
2189 let mut to = BTreeSet::new();
2190 to.insert(KeyId::parse("@bob").unwrap());
2191 let header = AttestationHeader {
2192 content_hash: hash_s.into(),
2193 performative: perf.into(),
2194 from: KeyId::parse("@alice").unwrap(),
2195 to,
2196 thread: thread_name.into(),
2197 caused_by: Some(CausedBy::Begin),
2198 };
2199 let signature = sign_attestation_v2(&SIGNER, &header).unwrap();
2200 RedactedEnvelope { header, signature }
2201 }
2202
2203 #[test]
2206 fn envelope_is_placed_by_its_authenticated_thread() {
2207 let mut store = ThreadedMessageStore::new();
2208 assert_eq!(
2209 store.append_envelope(env("h1", "offer", "t1"), &SIGNER),
2210 Ok(true)
2211 );
2212 assert!(store
2213 .envelope_in_thread(&hash("h1"), &thread("t1"))
2214 .is_some());
2215 assert!(store
2217 .envelope_in_thread(&hash("h1"), &thread("t2"))
2218 .is_none());
2219 assert!(store.lookup_in_thread(&hash("h1"), &thread("t1")).is_none());
2221 assert!(!store.contains(&hash("h1"), &thread("t1")));
2222 }
2223
2224 #[test]
2228 fn relabelled_envelope_is_a_signature_failure_and_not_stored() {
2229 let mut store = ThreadedMessageStore::new();
2230 let mut e = env("h1", "offer", "t1");
2231 e.header.thread = String::from("t2"); assert_eq!(
2233 store.append_envelope(e, &SIGNER),
2234 Err(crate::attest::AttestError::InvalidSignature)
2235 );
2236 assert!(store
2237 .envelope_in_thread(&hash("h1"), &thread("t1"))
2238 .is_none());
2239 assert!(store
2240 .envelope_in_thread(&hash("h1"), &thread("t2"))
2241 .is_none());
2242 }
2243
2244 #[test]
2245 fn envelope_shelf_deduplicates_by_content_hash() {
2246 let mut store = ThreadedMessageStore::new();
2247 assert_eq!(
2248 store.append_envelope(env("h1", "offer", "t1"), &SIGNER),
2249 Ok(true)
2250 );
2251 assert_eq!(
2252 store.append_envelope(env("h1", "offer", "t1"), &SIGNER),
2253 Ok(false)
2254 );
2255 }
2256
2257 #[test]
2260 fn default_envelope_lookup_is_none() {
2261 struct NullStore;
2262 impl MessageStore for NullStore {
2263 fn lookup(&self, _: &ContentHash) -> Option<&Message> {
2264 None
2265 }
2266 fn lookup_in_thread(&self, _: &ContentHash, _: &ThreadId) -> Option<&Message> {
2267 None
2268 }
2269 fn contains(&self, _: &ContentHash, _: &ThreadId) -> bool {
2270 false
2271 }
2272 fn append(&mut self, _: ContentHash, _: ThreadId, _: Message) -> bool {
2273 false
2274 }
2275 fn frontier(&self, _: &ThreadId) -> Vec<&ContentHash> {
2276 Vec::new()
2277 }
2278 fn causal_closure(&self, _: &ContentHash, _: &ThreadId) -> Vec<ContentHash> {
2279 Vec::new()
2280 }
2281 }
2282 assert!(NullStore
2283 .envelope_in_thread(&hash("h1"), &thread("t1"))
2284 .is_none());
2285 assert!(NullStore
2287 .opened_in_thread(&hash("h1"), &thread("t1"))
2288 .is_none());
2289 }
2290
2291 use crate::envelope::{build_opened, OpenedError, HEADER_FIELDS};
2296 use crate::keyid::SignatureSuite;
2297 use crate::message::Recipients;
2299 use crate::typed_addr::{typed_root, FieldId};
2300
2301 fn opened(perf: &str, thread_name: &str) -> (crate::envelope::OpenedEnvelope, String) {
2304 let mut to = alloc::collections::BTreeSet::new();
2305 to.insert("@bob".to_string());
2306 let m = Message::Simple {
2307 performative: Performative::Custom(perf.into()),
2308 recipient: Some(Recipients::Set(to)),
2309 content: SExpr::Atom(Atom::Str("secret".into())),
2310 params: Vec::new(),
2311 thread: Some(thread_name.into()),
2312 sender: Some("@alice".into()),
2313 caused_by: Some(CausedBy::Begin),
2314 };
2315 let root = typed_root(&m);
2316 let env = build_opened(&m, &HEADER_FIELDS, &SignatureSuite::Ed25519, &SIGNER).unwrap();
2317 (env, root)
2318 }
2319
2320 #[test]
2323 fn opened_envelope_is_placed_by_its_authenticated_thread() {
2324 let mut store = ThreadedMessageStore::new();
2325 let (env, root) = opened("offer", "t1");
2326 assert_eq!(store.append_opened(env, &SIGNER), Ok(true));
2327 assert!(store
2328 .opened_in_thread(&hash(&root), &thread("t1"))
2329 .is_some());
2330 assert!(store
2332 .opened_in_thread(&hash(&root), &thread("t2"))
2333 .is_none());
2334 assert!(store
2335 .lookup_in_thread(&hash(&root), &thread("t1"))
2336 .is_none());
2337 }
2338
2339 #[test]
2343 fn relabelled_opened_envelope_is_a_signature_failure_and_not_stored() {
2344 let mut store = ThreadedMessageStore::new();
2345 let (mut env, root) = opened("offer", "t1");
2346 for op in &mut env.openings {
2347 if op.field == FieldId::Thread {
2348 op.value = SExpr::List(vec![SExpr::Atom(Atom::Str("t2".to_string()))]);
2349 }
2350 }
2351 assert_eq!(
2352 store.append_opened(env, &SIGNER),
2353 Err(OpenedError::OpeningFailed {
2354 field: FieldId::Thread
2355 })
2356 );
2357 assert!(store
2358 .opened_in_thread(&hash(&root), &thread("t1"))
2359 .is_none());
2360 assert!(store
2361 .opened_in_thread(&hash(&root), &thread("t2"))
2362 .is_none());
2363 }
2364
2365 #[test]
2366 fn opened_shelf_deduplicates_by_root() {
2367 let mut store = ThreadedMessageStore::new();
2368 let (env1, _) = opened("offer", "t1");
2369 let (env2, _) = opened("offer", "t1");
2370 assert_eq!(store.append_opened(env1, &SIGNER), Ok(true));
2371 assert_eq!(store.append_opened(env2, &SIGNER), Ok(false));
2372 }
2373}