1#![forbid(unsafe_code)]
11
12use alloc::string::String;
13use alloc::vec::Vec;
14use core::fmt;
15
16use crate::protocol::CausalViolation;
17use crate::sexpr::{Atom, SExpr};
18use crate::shape::{ShapeConstraint, ShapeViolation};
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
31pub enum BlameParty {
32 Sender,
33 DialectAuthor,
34 Installer,
35}
36
37impl BlameParty {
38 pub fn as_str(&self) -> &'static str {
40 match self {
41 BlameParty::Sender => "sender",
42 BlameParty::DialectAuthor => "dialect-author",
43 BlameParty::Installer => "installer",
44 }
45 }
46}
47
48impl fmt::Display for BlameParty {
49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50 f.write_str(self.as_str())
51 }
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
61pub enum ViolationKind {
62 ResourceLimit,
64 Shape,
66 Causal,
68 R5,
70}
71
72impl ViolationKind {
73 pub fn as_str(&self) -> &'static str {
75 match self {
76 ViolationKind::ResourceLimit => "resource-limit",
77 ViolationKind::Shape => "shape",
78 ViolationKind::Causal => "causal",
79 ViolationKind::R5 => "r5",
80 }
81 }
82
83 pub fn as_violation_type(&self) -> &'static str {
86 match self {
87 ViolationKind::ResourceLimit => "resource-limit",
88 ViolationKind::Shape => "shape-violation",
89 ViolationKind::Causal => "causal-violation",
90 ViolationKind::R5 => "r5-violation",
91 }
92 }
93}
94
95impl fmt::Display for ViolationKind {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 f.write_str(self.as_str())
98 }
99}
100
101#[derive(Debug, Clone, PartialEq, Eq)]
107#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
108pub struct BlameEntry {
109 pub party: BlameParty,
111 pub reason: String,
113 pub evidence: Option<SExpr>,
115}
116
117impl BlameEntry {
118 pub fn to_sexpr(&self) -> SExpr {
124 let mut items: Vec<SExpr> = alloc::vec![
125 SExpr::Atom(Atom::Symbol(String::from("blame"))),
126 SExpr::Atom(Atom::Keyword(String::from("party"))),
127 SExpr::Atom(Atom::Symbol(String::from(self.party.as_str()))),
128 SExpr::Atom(Atom::Keyword(String::from("reason"))),
129 SExpr::Atom(Atom::Str(self.reason.clone())),
130 ];
131 if let Some(ref ev) = self.evidence {
132 items.push(SExpr::Atom(Atom::Keyword(String::from("evidence"))));
133 items.push(ev.clone());
134 }
135 SExpr::List(items)
136 }
137}
138
139#[derive(Debug, Clone, PartialEq, Eq)]
149#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
150pub struct ViolationError {
151 pub kind: ViolationKind,
153 pub blame_chain: Vec<BlameEntry>,
155 pub detail: String,
157
158 pub recipient: Option<String>,
162 pub dialect: Option<String>,
164 pub dialect_author: Option<String>,
166 pub dialect_hash: Option<String>,
168 pub performative: Option<String>,
170 pub verifier: Option<String>,
172 pub message_hash: Option<String>,
174 pub caused_by: Option<String>,
176 pub rule: Option<String>,
178 pub field: Option<String>,
180 pub expected: Option<String>,
182 pub found: Option<String>,
184
185 pub thread_id: Option<String>,
189}
190
191impl fmt::Display for ViolationError {
192 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193 write!(f, "{} violation: {}", self.kind, self.detail)
194 }
195}
196
197impl ViolationError {
202 fn new(kind: ViolationKind, detail: String, blame_chain: Vec<BlameEntry>) -> Self {
205 ViolationError {
206 kind,
207 blame_chain,
208 detail,
209 recipient: None,
210 dialect: None,
211 dialect_author: None,
212 dialect_hash: None,
213 performative: None,
214 verifier: None,
215 message_hash: None,
216 caused_by: None,
217 rule: None,
218 field: None,
219 expected: None,
220 found: None,
221 thread_id: None,
222 }
223 }
224
225 pub fn with_recipient(mut self, recipient: impl Into<String>) -> Self {
227 self.recipient = Some(recipient.into());
228 self
229 }
230
231 pub fn with_verifier(mut self, verifier: impl Into<String>) -> Self {
233 self.verifier = Some(verifier.into());
234 self
235 }
236
237 pub fn with_dialect_context(
240 mut self,
241 dialect_name: &str,
242 dialect_author: Option<&str>,
243 dialect_hash: Option<&str>,
244 performative: Option<&str>,
245 ) -> Self {
246 self.dialect = Some(String::from(dialect_name));
247 self.dialect_author = dialect_author.map(String::from);
248 self.dialect_hash = dialect_hash.map(String::from);
249 if let Some(p) = performative {
250 self.performative = Some(String::from(p));
251 }
252 self
253 }
254
255 pub fn with_message_hash(mut self, hash: impl Into<String>) -> Self {
257 self.message_hash = Some(hash.into());
258 self
259 }
260
261 pub fn with_thread_id(mut self, thread: impl Into<String>) -> Self {
263 self.thread_id = Some(thread.into());
264 self
265 }
266
267 pub fn from_shape_violation(
273 violation: &ShapeViolation,
274 message_hash: Option<String>,
275 thread_id: Option<String>,
276 evidence: Option<SExpr>,
277 ) -> Self {
278 if violation.rule == "resource-limit" {
279 let mut err = Self::new(
280 ViolationKind::ResourceLimit,
281 violation.detail.clone(),
282 alloc::vec![],
283 );
284 err.field = violation.field.clone();
285 err.rule = Some("resource-limit".into());
286 err.message_hash = message_hash;
287 err.thread_id = thread_id;
288 return err;
289 }
290 let reason = alloc::format!(
291 "shape rule '{}' violated: {}",
292 violation.rule,
293 violation.detail
294 );
295 let mut err = Self::new(
296 ViolationKind::Shape,
297 alloc::format!("{}", violation),
298 alloc::vec![BlameEntry {
299 party: BlameParty::Sender,
300 reason,
301 evidence,
302 }],
303 );
304 err.message_hash = message_hash;
305 err.thread_id = thread_id;
306 err.rule = Some(violation.rule.clone());
307 err.field = violation.field.clone();
308 err.expected = violation.expected.clone();
309 err.found = violation.found.clone();
310 err
311 }
312
313 pub fn from_causal_violation(
319 violation: &CausalViolation,
320 message_hash: Option<String>,
321 thread_id: Option<String>,
322 ) -> Self {
323 let reason = alloc::format!("{}", violation);
324 let mut err = Self::new(
325 ViolationKind::Causal,
326 reason.clone(),
327 alloc::vec![BlameEntry {
328 party: BlameParty::Sender,
329 reason,
330 evidence: None,
331 }],
332 );
333 err.message_hash = message_hash;
334 err.thread_id = thread_id;
335 err.caused_by = match violation {
336 CausalViolation::UnknownPredecessor { caused_by } => Some(caused_by.clone()),
337 CausalViolation::InvalidPredecessor { caused_by, .. } => Some(caused_by.clone()),
338 _ => None,
339 };
340 err
341 }
342
343 pub fn from_unsatisfiable_shape(
352 dialect_name: &str,
353 constraint_summary: &str,
354 rationale: &str,
355 ) -> Self {
356 let detail = alloc::format!(
357 "dialect '{}' contains an unsatisfiable shape constraint: {}",
358 dialect_name,
359 constraint_summary
360 );
361 let reason = alloc::format!(
362 "shape constraint cannot be satisfied by any message: {}",
363 rationale
364 );
365 let mut err = Self::new(
366 ViolationKind::Shape,
367 detail,
368 alloc::vec![BlameEntry {
369 party: BlameParty::DialectAuthor,
370 reason,
371 evidence: None,
372 }],
373 );
374 err.dialect = Some(String::from(dialect_name));
375 err
376 }
377
378 pub fn from_r5_violation(dialect_name: &str, violations: &[String]) -> Self {
384 let detail = alloc::format!(
385 "dialect '{}' has {} R5 violation(s): {}",
386 dialect_name,
387 violations.len(),
388 violations.join("; ")
389 );
390
391 let author_reason =
392 alloc::format!("dialect '{}' contains well-formedness errors", dialect_name);
393 let installer_reason = alloc::format!(
394 "installed dialect '{}' without catching R5 violations",
395 dialect_name
396 );
397
398 let mut err = Self::new(
399 ViolationKind::R5,
400 detail,
401 alloc::vec![
402 BlameEntry {
403 party: BlameParty::DialectAuthor,
404 reason: author_reason,
405 evidence: None,
406 },
407 BlameEntry {
408 party: BlameParty::Installer,
409 reason: installer_reason,
410 evidence: None,
411 },
412 ],
413 );
414 err.dialect = Some(String::from(dialect_name));
415 err
416 }
417
418 pub fn to_sexpr(&self) -> SExpr {
441 let mut items: Vec<SExpr> = Vec::new();
442 items.push(SExpr::Atom(Atom::Symbol(String::from("error"))));
443
444 let recipient = self
446 .recipient
447 .clone()
448 .unwrap_or_else(|| String::from("@unknown"));
449 items.push(SExpr::Atom(Atom::Symbol(recipient)));
450
451 items.push(SExpr::Atom(Atom::Str(String::from(
453 self.kind.as_violation_type(),
454 ))));
455
456 let push_str_kv = |items: &mut Vec<SExpr>, key: &str, val: &str| {
458 items.push(SExpr::Atom(Atom::Keyword(String::from(key))));
459 items.push(SExpr::Atom(Atom::Str(String::from(val))));
460 };
461
462 if let Some(ref v) = self.dialect {
463 push_str_kv(&mut items, "dialect", v);
464 }
465 if let Some(ref v) = self.dialect_author {
466 push_str_kv(&mut items, "dialect-author", v);
467 }
468 if let Some(ref v) = self.dialect_hash {
469 push_str_kv(&mut items, "dialect-hash", v);
470 }
471 if let Some(ref v) = self.performative {
472 push_str_kv(&mut items, "performative", v);
473 }
474 if let Some(ref v) = self.rule {
475 push_str_kv(&mut items, "rule", v);
476 }
477 if let Some(ref v) = self.field {
478 items.push(SExpr::Atom(Atom::Keyword(String::from("field"))));
480 let stripped = v.strip_prefix(':').unwrap_or(v.as_str());
482 items.push(SExpr::Atom(Atom::Keyword(String::from(stripped))));
483 }
484 if let Some(ref v) = self.expected {
485 push_str_kv(&mut items, "expected", v);
486 }
487 if let Some(ref v) = self.found {
488 push_str_kv(&mut items, "found", v);
489 }
490
491 push_str_kv(&mut items, "detail", &self.detail);
493
494 if let Some(first) = self.blame_chain.first() {
496 items.push(SExpr::Atom(Atom::Keyword(String::from("blamed"))));
497 items.push(SExpr::Atom(Atom::Symbol(String::from(
498 first.party.as_str(),
499 ))));
500 }
501
502 if let Some(ref v) = self.verifier {
503 push_str_kv(&mut items, "verifier", v);
504 }
505 if let Some(ref v) = self.message_hash {
506 push_str_kv(&mut items, "message-hash", v);
507 }
508 if let Some(ref v) = self.caused_by {
509 push_str_kv(&mut items, "caused-by", v);
510 }
511
512 items.push(SExpr::Atom(Atom::Keyword(String::from("blame-chain"))));
514 let chain: Vec<SExpr> = self.blame_chain.iter().map(|e| e.to_sexpr()).collect();
515 items.push(SExpr::List(chain));
516
517 SExpr::List(items)
518 }
519
520 pub fn verify_blame(&self, shape_constraint: Option<&ShapeConstraint>) -> bool {
532 match self.kind {
533 ViolationKind::ResourceLimit => false,
534 ViolationKind::Shape => self.verify_shape_blame(shape_constraint),
535 ViolationKind::Causal => self.verify_causal_blame(),
536 ViolationKind::R5 => self.verify_r5_blame(),
537 }
538 }
539
540 fn verify_shape_blame(&self, shape_constraint: Option<&ShapeConstraint>) -> bool {
542 let constraint = match shape_constraint {
543 Some(c) => c,
544 None => return false,
545 };
546
547 for entry in &self.blame_chain {
550 if let Some(ref evidence) = entry.evidence {
551 if matches!(constraint.check(evidence), Err(ref e) if e.rule != "resource-limit") {
552 return true;
553 }
554 }
555 }
556 false
557 }
558
559 fn verify_causal_blame(&self) -> bool {
561 self.blame_chain
562 .iter()
563 .any(|e| e.party == BlameParty::Sender)
564 }
565
566 fn verify_r5_blame(&self) -> bool {
568 self.blame_chain
569 .iter()
570 .any(|e| e.party == BlameParty::DialectAuthor)
571 }
572
573 #[allow(unused_variables)]
587 pub fn record_metrics(&self, dialect: &str) {
588 #[cfg(feature = "tracing")]
589 {
590 for entry in &self.blame_chain {
592 tracing::event!(
593 tracing::Level::INFO,
594 dialect = dialect,
595 blamed_party = entry.party.as_str(),
596 violation_type = self.kind.as_str(),
597 "cbcl_blame_attribution_count"
598 );
599 }
600
601 let sexpr = self.to_sexpr();
603 let size = alloc::format!("{}", sexpr).len();
604 tracing::event!(
605 tracing::Level::INFO,
606 size_bytes = size,
607 violation_type = self.kind.as_str(),
608 dialect = dialect,
609 "cbcl_violation_error_size_bytes"
610 );
611 }
612 }
613}
614
615#[cfg(test)]
620mod tests {
621 use super::*;
622 use alloc::string::ToString;
623 use alloc::vec;
624
625 fn sym(s: &str) -> SExpr {
626 SExpr::Atom(Atom::Symbol(String::from(s)))
627 }
628
629 fn kw(s: &str) -> SExpr {
630 SExpr::Atom(Atom::Keyword(String::from(s)))
631 }
632
633 fn str_expr(s: &str) -> SExpr {
634 SExpr::Atom(Atom::Str(String::from(s)))
635 }
636
637 fn num(n: i64) -> SExpr {
638 SExpr::Atom(Atom::Num(n))
639 }
640
641 fn list(items: Vec<SExpr>) -> SExpr {
642 SExpr::List(items)
643 }
644
645 #[test]
648 fn blame_party_as_str() {
649 assert_eq!(BlameParty::Sender.as_str(), "sender");
650 assert_eq!(BlameParty::DialectAuthor.as_str(), "dialect-author");
651 assert_eq!(BlameParty::Installer.as_str(), "installer");
652 }
653
654 #[test]
655 fn blame_party_display() {
656 assert_eq!(BlameParty::Sender.to_string(), "sender");
657 assert_eq!(BlameParty::DialectAuthor.to_string(), "dialect-author");
658 assert_eq!(BlameParty::Installer.to_string(), "installer");
659 }
660
661 #[test]
664 fn violation_kind_as_str() {
665 assert_eq!(ViolationKind::Shape.as_str(), "shape");
666 assert_eq!(ViolationKind::Causal.as_str(), "causal");
667 assert_eq!(ViolationKind::R5.as_str(), "r5");
668 }
669
670 #[test]
671 fn violation_kind_display() {
672 assert_eq!(ViolationKind::Shape.to_string(), "shape");
673 assert_eq!(ViolationKind::Causal.to_string(), "causal");
674 assert_eq!(ViolationKind::R5.to_string(), "r5");
675 }
676
677 #[test]
680 fn blame_entry_to_sexpr_with_evidence() {
681 let entry = BlameEntry {
682 party: BlameParty::Sender,
683 reason: String::from("missing :target"),
684 evidence: Some(list(vec![sym("track"), kw("route"), str_expr("A")])),
685 };
686 let sexpr = entry.to_sexpr();
687 let s = alloc::format!("{}", sexpr);
688 assert!(s.contains("blame"));
689 assert!(s.contains(":party"));
690 assert!(s.contains("sender"));
691 assert!(s.contains(":reason"));
692 assert!(s.contains("missing :target"));
693 assert!(s.contains(":evidence"));
694 }
695
696 #[test]
697 fn blame_entry_to_sexpr_without_evidence() {
698 let entry = BlameEntry {
699 party: BlameParty::DialectAuthor,
700 reason: String::from("bad shape"),
701 evidence: None,
702 };
703 let sexpr = entry.to_sexpr();
704 let s = alloc::format!("{}", sexpr);
705 assert!(s.contains("dialect-author"));
706 assert!(!s.contains(":evidence"));
707 }
708
709 #[test]
712 fn from_shape_violation_blames_sender() {
713 let sv = ShapeViolation {
714 rule: String::from("require :target string"),
715 field: Some(String::from(":target")),
716 expected: Some(String::from("string")),
717 found: Some(String::from("number")),
718 detail: String::from("parameter :target expected type string, found number"),
719 };
720 let evidence = list(vec![sym("propose"), kw("target"), num(42)]);
721 let err = ViolationError::from_shape_violation(
722 &sv,
723 Some(String::from("abc123")),
724 Some(String::from("t1")),
725 Some(evidence),
726 );
727
728 assert_eq!(err.kind, ViolationKind::Shape);
729 assert_eq!(err.message_hash, Some(String::from("abc123")));
730 assert_eq!(err.thread_id, Some(String::from("t1")));
731 assert_eq!(err.blame_chain.len(), 1);
732 assert_eq!(err.blame_chain[0].party, BlameParty::Sender);
733 assert!(err.blame_chain[0].evidence.is_some());
734 assert!(err.detail.contains("shape violation"));
735 }
736
737 #[test]
740 fn from_causal_violation_blames_sender() {
741 let cv = CausalViolation::MissingCausedBy;
742 let err = ViolationError::from_causal_violation(
743 &cv,
744 Some(String::from("def456")),
745 Some(String::from("t2")),
746 );
747
748 assert_eq!(err.kind, ViolationKind::Causal);
749 assert_eq!(err.blame_chain.len(), 1);
750 assert_eq!(err.blame_chain[0].party, BlameParty::Sender);
751 assert!(err.detail.contains("caused-by"));
752 }
753
754 #[test]
755 fn from_causal_violation_unknown_predecessor() {
756 let cv = CausalViolation::UnknownPredecessor {
757 caused_by: String::from("hash999"),
758 };
759 let err = ViolationError::from_causal_violation(&cv, None, None);
760
761 assert_eq!(err.kind, ViolationKind::Causal);
762 assert!(err.detail.contains("hash999"));
763 }
764
765 #[test]
766 fn from_causal_violation_invalid_predecessor() {
767 let cv = CausalViolation::InvalidPredecessor {
768 caused_by: String::from("hash111"),
769 expected: alloc::vec![String::from("ask"), String::from("tell")],
770 found: String::from("reply"),
771 };
772 let err = ViolationError::from_causal_violation(&cv, None, None);
773
774 assert!(err.detail.contains("hash111"));
775 assert!(err.detail.contains("reply"));
776 }
777
778 #[test]
781 fn from_r5_violation_blames_author_and_installer() {
782 let violations = alloc::vec![
783 String::from("shape targets unknown performative 'foo'"),
784 String::from("cycle detected: a → b → a"),
785 ];
786 let err = ViolationError::from_r5_violation("bad-dialect", &violations);
787
788 assert_eq!(err.kind, ViolationKind::R5);
789 assert_eq!(err.blame_chain.len(), 2);
790 assert_eq!(err.blame_chain[0].party, BlameParty::DialectAuthor);
791 assert_eq!(err.blame_chain[1].party, BlameParty::Installer);
792 assert!(err.detail.contains("bad-dialect"));
793 assert!(err.detail.contains("2 R5 violation(s)"));
794 }
795
796 #[test]
799 fn from_unsatisfiable_shape_blames_dialect_author() {
800 let err = ViolationError::from_unsatisfiable_shape(
801 "logistics",
802 "require :route string AND require :route number",
803 "no value can satisfy both type constraints simultaneously",
804 );
805 assert_eq!(err.kind, ViolationKind::Shape);
806 assert_eq!(err.blame_chain.len(), 1);
807 assert_eq!(err.blame_chain[0].party, BlameParty::DialectAuthor);
808 assert!(err.blame_chain[0].evidence.is_none());
809 assert!(err.detail.contains("logistics"));
810 assert!(err.detail.contains("unsatisfiable"));
811 assert!(err.message_hash.is_none());
812 assert!(err.thread_id.is_none());
813 }
814
815 #[test]
818 fn to_sexpr_shape_violation() {
819 let sv = ShapeViolation {
820 rule: String::from("require :pkg string"),
821 field: Some(String::from(":pkg")),
822 expected: Some(String::from("string")),
823 found: Some(String::from("number")),
824 detail: String::from(":pkg expected string, found number"),
825 };
826 let err = ViolationError::from_shape_violation(
827 &sv,
828 Some(String::from("h1")),
829 Some(String::from("t1")),
830 Some(num(42)),
831 );
832 let sexpr = err.to_sexpr();
833 let s = alloc::format!("{}", sexpr);
834
835 assert!(s.starts_with("(error @unknown \"shape-violation\""));
837 assert!(s.contains(":detail"));
838 assert!(s.contains(":message-hash"));
839 assert!(s.contains("\"h1\""));
840 assert!(!s.contains(":thread"));
842 assert!(s.contains(":blame-chain"));
843 assert!(s.contains("(blame "));
844 assert!(s.contains(":rule"));
846 assert!(s.contains(":expected"));
847 assert!(s.contains(":found"));
848 }
849
850 #[test]
851 fn to_sexpr_without_optional_fields() {
852 let cv = CausalViolation::MissingCausedBy;
853 let err = ViolationError::from_causal_violation(&cv, None, None);
854 let sexpr = err.to_sexpr();
855 let s = alloc::format!("{}", sexpr);
856
857 assert!(s.starts_with("(error @unknown \"causal-violation\""));
858 assert!(!s.contains(":message-hash"));
859 assert!(!s.contains(":thread"));
860 assert!(!s.contains(":kind"));
862 }
863
864 #[test]
865 fn to_sexpr_r5_violation() {
866 let err = ViolationError::from_r5_violation("test-d", &[String::from("cycle found")]);
867 let sexpr = err.to_sexpr();
868 let s = alloc::format!("{}", sexpr);
869
870 assert!(s.starts_with("(error "));
871 assert!(s.contains("r5"));
872 assert!(s.contains(":blame-chain"));
873 let blame_count = s.matches("(blame ").count();
875 assert_eq!(blame_count, 2);
876 }
877
878 #[test]
881 fn to_sexpr_matches_req233_abnf() {
882 let sv = ShapeViolation {
883 rule: String::from("require :route string"),
884 field: Some(String::from(":route")),
885 expected: Some(String::from("string")),
886 found: Some(String::from("number")),
887 detail: String::from(":route expected string, found number"),
888 };
889 let err =
890 ViolationError::from_shape_violation(&sv, Some(String::from("f1220msg")), None, None)
891 .with_recipient("@sender")
892 .with_verifier("@receiver")
893 .with_dialect_context(
894 "logistics",
895 Some("@consortium"),
896 Some("f1220abc"),
897 Some("track-shipment"),
898 );
899 let s = alloc::format!("{}", err.to_sexpr());
900
901 assert!(s.starts_with("(error @sender \"shape-violation\""));
903 assert!(s.contains(":dialect "), "missing :dialect");
904 assert!(s.contains(":dialect-author "), "missing :dialect-author");
905 assert!(s.contains(":dialect-hash "), "missing :dialect-hash");
906 assert!(s.contains(":performative "), "missing :performative");
907 assert!(s.contains(":rule "), "missing :rule");
908 assert!(s.contains(":field "), "missing :field");
909 assert!(s.contains(":expected "), "missing :expected");
910 assert!(s.contains(":found "), "missing :found");
911 assert!(s.contains(":blamed sender"), "missing :blamed positional");
912 assert!(s.contains(":verifier "), "missing :verifier");
913 assert!(s.contains(":message-hash "), "missing :message-hash");
914 assert!(!s.contains(":kind"), "spec form has no :kind keyword");
915 assert!(!s.contains(":thread"), "spec form has no :thread keyword");
916 }
917
918 #[test]
920 fn to_sexpr_causal_includes_caused_by() {
921 let cv = CausalViolation::UnknownPredecessor {
922 caused_by: String::from("f1220pred"),
923 };
924 let err = ViolationError::from_causal_violation(&cv, None, None)
925 .with_recipient("@sender")
926 .with_dialect_context("d", None, None, Some("ack"));
927 let s = alloc::format!("{}", err.to_sexpr());
928 assert!(s.starts_with("(error @sender \"causal-violation\""));
929 assert!(s.contains(":caused-by"));
930 assert!(s.contains("\"f1220pred\""));
931 assert!(s.contains(":blamed sender"));
932 }
933
934 #[test]
938 fn to_sexpr_causal_invalid_predecessor_includes_caused_by() {
939 let cv = CausalViolation::InvalidPredecessor {
940 caused_by: String::from("f1220bad"),
941 expected: alloc::vec![String::from("pause")],
942 found: String::from("ack"),
943 };
944 let err = ViolationError::from_causal_violation(&cv, None, None);
945 assert_eq!(err.caused_by.as_deref(), Some("f1220bad"));
946 let s = alloc::format!("{}", err.to_sexpr());
947 assert!(s.contains(":caused-by"));
948 assert!(s.contains("\"f1220bad\""));
949 }
950
951 #[test]
954 fn to_sexpr_unsatisfiable_shape_blames_dialect_author() {
955 let err = ViolationError::from_unsatisfiable_shape(
956 "logistics",
957 "string AND number",
958 "no value satisfies both",
959 );
960 let s = alloc::format!("{}", err.to_sexpr());
961 assert!(s.starts_with("(error @unknown \"shape-violation\""));
962 assert!(s.contains(":blamed dialect-author"));
963 assert!(s.contains(":dialect "));
964 assert!(s.contains("\"logistics\""));
965 }
966
967 #[test]
970 fn to_sexpr_r5_violation_matches_abnf() {
971 let err = ViolationError::from_r5_violation(
972 "broken",
973 &alloc::vec![String::from("cycle: a → b → a")],
974 )
975 .with_recipient("@installer");
976 let s = alloc::format!("{}", err.to_sexpr());
977 assert!(s.starts_with("(error @installer \"r5-violation\""));
978 assert!(s.contains(":dialect "));
979 assert!(s.contains("\"broken\""));
980 assert!(s.contains(":blamed dialect-author"));
981 assert_eq!(s.matches("(blame ").count(), 2);
983 }
984
985 #[test]
988 fn to_sexpr_field_emits_keyword_atom() {
989 let sv = ShapeViolation {
990 rule: String::from("require :route string"),
991 field: Some(String::from(":route")),
992 expected: None,
993 found: None,
994 detail: String::from("test"),
995 };
996 let err = ViolationError::from_shape_violation(&sv, None, None, None);
997 let sexpr = err.to_sexpr();
998
999 let items = match sexpr {
1001 SExpr::List(items) => items,
1002 _ => panic!("error must be a list"),
1003 };
1004 let mut idx = None;
1005 for (i, item) in items.iter().enumerate() {
1006 if matches!(item, SExpr::Atom(Atom::Keyword(k)) if k == "field") {
1007 idx = Some(i);
1008 break;
1009 }
1010 }
1011 let i = idx.expect(":field keyword must be present");
1012 let value = &items[i + 1];
1013 match value {
1015 SExpr::Atom(Atom::Keyword(k)) => assert_eq!(k, "route"),
1016 other => panic!(":field value must be a Keyword atom, got {other:?}"),
1017 }
1018 }
1019
1020 #[test]
1023 fn with_recipient_sets_recipient() {
1024 let cv = CausalViolation::MissingCausedBy;
1025 let err = ViolationError::from_causal_violation(&cv, None, None).with_recipient("@alice");
1026 assert_eq!(err.recipient.as_deref(), Some("@alice"));
1027 }
1028
1029 #[test]
1030 fn with_verifier_sets_verifier() {
1031 let cv = CausalViolation::MissingCausedBy;
1032 let err = ViolationError::from_causal_violation(&cv, None, None).with_verifier("@bob");
1033 assert_eq!(err.verifier.as_deref(), Some("@bob"));
1034 }
1035
1036 #[test]
1037 fn with_message_hash_sets_message_hash() {
1038 let cv = CausalViolation::MissingCausedBy;
1039 let err =
1040 ViolationError::from_causal_violation(&cv, None, None).with_message_hash("f1220msg");
1041 assert_eq!(err.message_hash.as_deref(), Some("f1220msg"));
1042 }
1043
1044 #[test]
1045 fn with_thread_id_sets_thread_id_but_does_not_emit() {
1046 let cv = CausalViolation::MissingCausedBy;
1047 let err = ViolationError::from_causal_violation(&cv, None, None).with_thread_id("t-7");
1048 assert_eq!(err.thread_id.as_deref(), Some("t-7"));
1049 let s = alloc::format!("{}", err.to_sexpr());
1050 assert!(!s.contains(":thread"));
1051 assert!(!s.contains("t-7"));
1052 }
1053
1054 #[test]
1055 fn with_dialect_context_sets_all_fields() {
1056 let cv = CausalViolation::MissingCausedBy;
1057 let err = ViolationError::from_causal_violation(&cv, None, None).with_dialect_context(
1058 "d",
1059 Some("@a"),
1060 Some("h"),
1061 Some("p"),
1062 );
1063 assert_eq!(err.dialect.as_deref(), Some("d"));
1064 assert_eq!(err.dialect_author.as_deref(), Some("@a"));
1065 assert_eq!(err.dialect_hash.as_deref(), Some("h"));
1066 assert_eq!(err.performative.as_deref(), Some("p"));
1067 }
1068
1069 #[test]
1070 fn with_dialect_context_handles_optional_fields() {
1071 let cv = CausalViolation::MissingCausedBy;
1072 let err = ViolationError::from_causal_violation(&cv, None, None)
1073 .with_dialect_context("d", None, None, None);
1074 assert_eq!(err.dialect.as_deref(), Some("d"));
1075 assert_eq!(err.dialect_author, None);
1076 assert_eq!(err.dialect_hash, None);
1077 assert_eq!(err.performative, None);
1078 }
1079
1080 #[test]
1083 fn violation_error_display() {
1084 let cv = CausalViolation::MissingCausedBy;
1085 let err = ViolationError::from_causal_violation(&cv, None, None);
1086 let s = err.to_string();
1087 assert!(s.contains("causal violation"));
1088 }
1089
1090 #[test]
1093 fn verify_blame_shape_with_valid_evidence() {
1094 use crate::shape::{ShapeConstraint, ShapeRule, TypeConstraint};
1095
1096 let constraint = ShapeConstraint {
1097 performative: String::from("track"),
1098 rules: vec![ShapeRule::Require {
1099 keyword: String::from("package"),
1100 type_constraint: Some(TypeConstraint::String),
1101 children: vec![],
1102 }],
1103 };
1104
1105 let evidence = list(vec![sym("track"), kw("package"), num(42)]);
1107 let sv = ShapeViolation {
1108 rule: String::from("require :package string"),
1109 field: Some(String::from(":package")),
1110 expected: Some(String::from("string")),
1111 found: Some(String::from("number")),
1112 detail: String::from(":package expected string, found number"),
1113 };
1114 let err = ViolationError::from_shape_violation(&sv, None, None, Some(evidence));
1115
1116 assert!(err.verify_blame(Some(&constraint)));
1117 }
1118
1119 #[test]
1120 fn verify_blame_shape_with_passing_evidence_returns_false() {
1121 use crate::shape::{ShapeConstraint, ShapeRule, TypeConstraint};
1122
1123 let constraint = ShapeConstraint {
1124 performative: String::from("track"),
1125 rules: vec![ShapeRule::Require {
1126 keyword: String::from("package"),
1127 type_constraint: Some(TypeConstraint::String),
1128 children: vec![],
1129 }],
1130 };
1131
1132 let evidence = list(vec![sym("track"), kw("package"), str_expr("box-1")]);
1134 let sv = ShapeViolation {
1135 rule: String::from("require :package string"),
1136 field: Some(String::from(":package")),
1137 expected: Some(String::from("string")),
1138 found: Some(String::from("number")),
1139 detail: String::from("fabricated violation"),
1140 };
1141 let err = ViolationError::from_shape_violation(&sv, None, None, Some(evidence));
1142
1143 assert!(!err.verify_blame(Some(&constraint)));
1144 }
1145
1146 #[test]
1147 fn verify_blame_shape_without_constraint_returns_false() {
1148 let sv = ShapeViolation {
1149 rule: String::from("require :x"),
1150 field: None,
1151 expected: None,
1152 found: None,
1153 detail: String::from("missing"),
1154 };
1155 let err = ViolationError::from_shape_violation(&sv, None, None, Some(sym("x")));
1156 assert!(!err.verify_blame(None));
1157 }
1158
1159 #[test]
1160 fn verify_blame_shape_without_evidence_returns_false() {
1161 use crate::shape::{ShapeConstraint, ShapeRule, TypeConstraint};
1162
1163 let constraint = ShapeConstraint {
1164 performative: String::from("track"),
1165 rules: vec![ShapeRule::Require {
1166 keyword: String::from("package"),
1167 type_constraint: Some(TypeConstraint::String),
1168 children: vec![],
1169 }],
1170 };
1171
1172 let sv = ShapeViolation {
1173 rule: String::from("require :package string"),
1174 field: None,
1175 expected: None,
1176 found: None,
1177 detail: String::from("missing"),
1178 };
1179 let err = ViolationError::from_shape_violation(&sv, None, None, None);
1180 assert!(!err.verify_blame(Some(&constraint)));
1181 }
1182
1183 #[test]
1184 fn verify_blame_causal() {
1185 let cv = CausalViolation::MissingCausedBy;
1186 let err = ViolationError::from_causal_violation(&cv, None, None);
1187 assert!(err.verify_blame(None));
1188 }
1189
1190 #[test]
1191 fn verify_blame_r5() {
1192 let err = ViolationError::from_r5_violation("d", &[String::from("bad")]);
1193 assert!(err.verify_blame(None));
1194 }
1195
1196 #[test]
1197 fn verify_blame_r5_without_author_returns_false() {
1198 let mut err = ViolationError::from_r5_violation("d", &[String::from("x")]);
1200 err.blame_chain = vec![BlameEntry {
1201 party: BlameParty::Installer,
1202 reason: String::from("installed bad dialect"),
1203 evidence: None,
1204 }];
1205 assert!(!err.verify_blame(None));
1206 }
1207
1208 #[test]
1209 fn verify_blame_causal_without_sender_returns_false() {
1210 let cv = CausalViolation::MissingCausedBy;
1211 let mut err = ViolationError::from_causal_violation(&cv, None, None);
1212 err.blame_chain = vec![BlameEntry {
1213 party: BlameParty::DialectAuthor,
1214 reason: String::from("wrong party"),
1215 evidence: None,
1216 }];
1217 assert!(!err.verify_blame(None));
1218 }
1219
1220 #[test]
1223 fn blame_party_copy_and_eq() {
1224 let a = BlameParty::Sender;
1225 let b = a; assert_eq!(a, b);
1227 }
1228
1229 #[test]
1230 fn violation_error_clone_and_eq() {
1231 let err = ViolationError::from_r5_violation("d", &[String::from("x")]);
1232 let err2 = err.clone();
1233 assert_eq!(err, err2);
1234 }
1235
1236 #[test]
1239 fn record_metrics_does_not_panic_shape() {
1240 let sv = ShapeViolation {
1241 rule: String::from("require :x string"),
1242 field: Some(String::from(":x")),
1243 expected: Some(String::from("string")),
1244 found: Some(String::from("number")),
1245 detail: String::from(":x expected string, found number"),
1246 };
1247 let err = ViolationError::from_shape_violation(
1248 &sv,
1249 Some(String::from("h1")),
1250 Some(String::from("t1")),
1251 Some(num(42)),
1252 );
1253 err.record_metrics("test-dialect");
1255 }
1256
1257 #[test]
1258 fn record_metrics_does_not_panic_causal() {
1259 let cv = CausalViolation::MissingCausedBy;
1260 let err = ViolationError::from_causal_violation(&cv, None, None);
1261 err.record_metrics("test-dialect");
1262 }
1263
1264 #[test]
1265 fn record_metrics_does_not_panic_r5() {
1266 let err = ViolationError::from_r5_violation("bad-d", &[String::from("cycle")]);
1267 err.record_metrics("bad-d");
1269 }
1270}