#![forbid(unsafe_code)]
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use crate::protocol::CausalViolation;
use crate::sexpr::{Atom, SExpr};
use crate::shape::{ShapeConstraint, ShapeViolation};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum BlameParty {
Sender,
DialectAuthor,
Installer,
}
impl BlameParty {
pub fn as_str(&self) -> &'static str {
match self {
BlameParty::Sender => "sender",
BlameParty::DialectAuthor => "dialect-author",
BlameParty::Installer => "installer",
}
}
}
impl fmt::Display for BlameParty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ViolationKind {
ResourceLimit,
Shape,
Causal,
R5,
}
impl ViolationKind {
pub fn as_str(&self) -> &'static str {
match self {
ViolationKind::ResourceLimit => "resource-limit",
ViolationKind::Shape => "shape",
ViolationKind::Causal => "causal",
ViolationKind::R5 => "r5",
}
}
pub fn as_violation_type(&self) -> &'static str {
match self {
ViolationKind::ResourceLimit => "resource-limit",
ViolationKind::Shape => "shape-violation",
ViolationKind::Causal => "causal-violation",
ViolationKind::R5 => "r5-violation",
}
}
}
impl fmt::Display for ViolationKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BlameEntry {
pub party: BlameParty,
pub reason: String,
pub evidence: Option<SExpr>,
}
impl BlameEntry {
pub fn to_sexpr(&self) -> SExpr {
let mut items: Vec<SExpr> = alloc::vec![
SExpr::Atom(Atom::Symbol(String::from("blame"))),
SExpr::Atom(Atom::Keyword(String::from("party"))),
SExpr::Atom(Atom::Symbol(String::from(self.party.as_str()))),
SExpr::Atom(Atom::Keyword(String::from("reason"))),
SExpr::Atom(Atom::Str(self.reason.clone())),
];
if let Some(ref ev) = self.evidence {
items.push(SExpr::Atom(Atom::Keyword(String::from("evidence"))));
items.push(ev.clone());
}
SExpr::List(items)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ViolationError {
pub kind: ViolationKind,
pub blame_chain: Vec<BlameEntry>,
pub detail: String,
pub recipient: Option<String>,
pub dialect: Option<String>,
pub dialect_author: Option<String>,
pub dialect_hash: Option<String>,
pub performative: Option<String>,
pub verifier: Option<String>,
pub message_hash: Option<String>,
pub caused_by: Option<String>,
pub rule: Option<String>,
pub field: Option<String>,
pub expected: Option<String>,
pub found: Option<String>,
pub thread_id: Option<String>,
}
impl fmt::Display for ViolationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} violation: {}", self.kind, self.detail)
}
}
impl ViolationError {
fn new(kind: ViolationKind, detail: String, blame_chain: Vec<BlameEntry>) -> Self {
ViolationError {
kind,
blame_chain,
detail,
recipient: None,
dialect: None,
dialect_author: None,
dialect_hash: None,
performative: None,
verifier: None,
message_hash: None,
caused_by: None,
rule: None,
field: None,
expected: None,
found: None,
thread_id: None,
}
}
pub fn with_recipient(mut self, recipient: impl Into<String>) -> Self {
self.recipient = Some(recipient.into());
self
}
pub fn with_verifier(mut self, verifier: impl Into<String>) -> Self {
self.verifier = Some(verifier.into());
self
}
pub fn with_dialect_context(
mut self,
dialect_name: &str,
dialect_author: Option<&str>,
dialect_hash: Option<&str>,
performative: Option<&str>,
) -> Self {
self.dialect = Some(String::from(dialect_name));
self.dialect_author = dialect_author.map(String::from);
self.dialect_hash = dialect_hash.map(String::from);
if let Some(p) = performative {
self.performative = Some(String::from(p));
}
self
}
pub fn with_message_hash(mut self, hash: impl Into<String>) -> Self {
self.message_hash = Some(hash.into());
self
}
pub fn with_thread_id(mut self, thread: impl Into<String>) -> Self {
self.thread_id = Some(thread.into());
self
}
pub fn from_shape_violation(
violation: &ShapeViolation,
message_hash: Option<String>,
thread_id: Option<String>,
evidence: Option<SExpr>,
) -> Self {
if violation.rule == "resource-limit" {
let mut err = Self::new(
ViolationKind::ResourceLimit,
violation.detail.clone(),
alloc::vec![],
);
err.field = violation.field.clone();
err.rule = Some("resource-limit".into());
err.message_hash = message_hash;
err.thread_id = thread_id;
return err;
}
let reason = alloc::format!(
"shape rule '{}' violated: {}",
violation.rule,
violation.detail
);
let mut err = Self::new(
ViolationKind::Shape,
alloc::format!("{}", violation),
alloc::vec![BlameEntry {
party: BlameParty::Sender,
reason,
evidence,
}],
);
err.message_hash = message_hash;
err.thread_id = thread_id;
err.rule = Some(violation.rule.clone());
err.field = violation.field.clone();
err.expected = violation.expected.clone();
err.found = violation.found.clone();
err
}
pub fn from_causal_violation(
violation: &CausalViolation,
message_hash: Option<String>,
thread_id: Option<String>,
) -> Self {
let reason = alloc::format!("{}", violation);
let mut err = Self::new(
ViolationKind::Causal,
reason.clone(),
alloc::vec![BlameEntry {
party: BlameParty::Sender,
reason,
evidence: None,
}],
);
err.message_hash = message_hash;
err.thread_id = thread_id;
err.caused_by = match violation {
CausalViolation::UnknownPredecessor { caused_by } => Some(caused_by.clone()),
CausalViolation::InvalidPredecessor { caused_by, .. } => Some(caused_by.clone()),
_ => None,
};
err
}
pub fn from_unsatisfiable_shape(
dialect_name: &str,
constraint_summary: &str,
rationale: &str,
) -> Self {
let detail = alloc::format!(
"dialect '{}' contains an unsatisfiable shape constraint: {}",
dialect_name,
constraint_summary
);
let reason = alloc::format!(
"shape constraint cannot be satisfied by any message: {}",
rationale
);
let mut err = Self::new(
ViolationKind::Shape,
detail,
alloc::vec![BlameEntry {
party: BlameParty::DialectAuthor,
reason,
evidence: None,
}],
);
err.dialect = Some(String::from(dialect_name));
err
}
pub fn from_r5_violation(dialect_name: &str, violations: &[String]) -> Self {
let detail = alloc::format!(
"dialect '{}' has {} R5 violation(s): {}",
dialect_name,
violations.len(),
violations.join("; ")
);
let author_reason =
alloc::format!("dialect '{}' contains well-formedness errors", dialect_name);
let installer_reason = alloc::format!(
"installed dialect '{}' without catching R5 violations",
dialect_name
);
let mut err = Self::new(
ViolationKind::R5,
detail,
alloc::vec![
BlameEntry {
party: BlameParty::DialectAuthor,
reason: author_reason,
evidence: None,
},
BlameEntry {
party: BlameParty::Installer,
reason: installer_reason,
evidence: None,
},
],
);
err.dialect = Some(String::from(dialect_name));
err
}
pub fn to_sexpr(&self) -> SExpr {
let mut items: Vec<SExpr> = Vec::new();
items.push(SExpr::Atom(Atom::Symbol(String::from("error"))));
let recipient = self
.recipient
.clone()
.unwrap_or_else(|| String::from("@unknown"));
items.push(SExpr::Atom(Atom::Symbol(recipient)));
items.push(SExpr::Atom(Atom::Str(String::from(
self.kind.as_violation_type(),
))));
let push_str_kv = |items: &mut Vec<SExpr>, key: &str, val: &str| {
items.push(SExpr::Atom(Atom::Keyword(String::from(key))));
items.push(SExpr::Atom(Atom::Str(String::from(val))));
};
if let Some(ref v) = self.dialect {
push_str_kv(&mut items, "dialect", v);
}
if let Some(ref v) = self.dialect_author {
push_str_kv(&mut items, "dialect-author", v);
}
if let Some(ref v) = self.dialect_hash {
push_str_kv(&mut items, "dialect-hash", v);
}
if let Some(ref v) = self.performative {
push_str_kv(&mut items, "performative", v);
}
if let Some(ref v) = self.rule {
push_str_kv(&mut items, "rule", v);
}
if let Some(ref v) = self.field {
items.push(SExpr::Atom(Atom::Keyword(String::from("field"))));
let stripped = v.strip_prefix(':').unwrap_or(v.as_str());
items.push(SExpr::Atom(Atom::Keyword(String::from(stripped))));
}
if let Some(ref v) = self.expected {
push_str_kv(&mut items, "expected", v);
}
if let Some(ref v) = self.found {
push_str_kv(&mut items, "found", v);
}
push_str_kv(&mut items, "detail", &self.detail);
if let Some(first) = self.blame_chain.first() {
items.push(SExpr::Atom(Atom::Keyword(String::from("blamed"))));
items.push(SExpr::Atom(Atom::Symbol(String::from(
first.party.as_str(),
))));
}
if let Some(ref v) = self.verifier {
push_str_kv(&mut items, "verifier", v);
}
if let Some(ref v) = self.message_hash {
push_str_kv(&mut items, "message-hash", v);
}
if let Some(ref v) = self.caused_by {
push_str_kv(&mut items, "caused-by", v);
}
items.push(SExpr::Atom(Atom::Keyword(String::from("blame-chain"))));
let chain: Vec<SExpr> = self.blame_chain.iter().map(|e| e.to_sexpr()).collect();
items.push(SExpr::List(chain));
SExpr::List(items)
}
pub fn verify_blame(&self, shape_constraint: Option<&ShapeConstraint>) -> bool {
match self.kind {
ViolationKind::ResourceLimit => false,
ViolationKind::Shape => self.verify_shape_blame(shape_constraint),
ViolationKind::Causal => self.verify_causal_blame(),
ViolationKind::R5 => self.verify_r5_blame(),
}
}
fn verify_shape_blame(&self, shape_constraint: Option<&ShapeConstraint>) -> bool {
let constraint = match shape_constraint {
Some(c) => c,
None => return false,
};
for entry in &self.blame_chain {
if let Some(ref evidence) = entry.evidence {
if matches!(constraint.check(evidence), Err(ref e) if e.rule != "resource-limit") {
return true;
}
}
}
false
}
fn verify_causal_blame(&self) -> bool {
self.blame_chain
.iter()
.any(|e| e.party == BlameParty::Sender)
}
fn verify_r5_blame(&self) -> bool {
self.blame_chain
.iter()
.any(|e| e.party == BlameParty::DialectAuthor)
}
#[allow(unused_variables)]
pub fn record_metrics(&self, dialect: &str) {
#[cfg(feature = "tracing")]
{
for entry in &self.blame_chain {
tracing::event!(
tracing::Level::INFO,
dialect = dialect,
blamed_party = entry.party.as_str(),
violation_type = self.kind.as_str(),
"cbcl_blame_attribution_count"
);
}
let sexpr = self.to_sexpr();
let size = alloc::format!("{}", sexpr).len();
tracing::event!(
tracing::Level::INFO,
size_bytes = size,
violation_type = self.kind.as_str(),
dialect = dialect,
"cbcl_violation_error_size_bytes"
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::string::ToString;
use alloc::vec;
fn sym(s: &str) -> SExpr {
SExpr::Atom(Atom::Symbol(String::from(s)))
}
fn kw(s: &str) -> SExpr {
SExpr::Atom(Atom::Keyword(String::from(s)))
}
fn str_expr(s: &str) -> SExpr {
SExpr::Atom(Atom::Str(String::from(s)))
}
fn num(n: i64) -> SExpr {
SExpr::Atom(Atom::Num(n))
}
fn list(items: Vec<SExpr>) -> SExpr {
SExpr::List(items)
}
#[test]
fn blame_party_as_str() {
assert_eq!(BlameParty::Sender.as_str(), "sender");
assert_eq!(BlameParty::DialectAuthor.as_str(), "dialect-author");
assert_eq!(BlameParty::Installer.as_str(), "installer");
}
#[test]
fn blame_party_display() {
assert_eq!(BlameParty::Sender.to_string(), "sender");
assert_eq!(BlameParty::DialectAuthor.to_string(), "dialect-author");
assert_eq!(BlameParty::Installer.to_string(), "installer");
}
#[test]
fn violation_kind_as_str() {
assert_eq!(ViolationKind::Shape.as_str(), "shape");
assert_eq!(ViolationKind::Causal.as_str(), "causal");
assert_eq!(ViolationKind::R5.as_str(), "r5");
}
#[test]
fn violation_kind_display() {
assert_eq!(ViolationKind::Shape.to_string(), "shape");
assert_eq!(ViolationKind::Causal.to_string(), "causal");
assert_eq!(ViolationKind::R5.to_string(), "r5");
}
#[test]
fn blame_entry_to_sexpr_with_evidence() {
let entry = BlameEntry {
party: BlameParty::Sender,
reason: String::from("missing :target"),
evidence: Some(list(vec![sym("track"), kw("route"), str_expr("A")])),
};
let sexpr = entry.to_sexpr();
let s = alloc::format!("{}", sexpr);
assert!(s.contains("blame"));
assert!(s.contains(":party"));
assert!(s.contains("sender"));
assert!(s.contains(":reason"));
assert!(s.contains("missing :target"));
assert!(s.contains(":evidence"));
}
#[test]
fn blame_entry_to_sexpr_without_evidence() {
let entry = BlameEntry {
party: BlameParty::DialectAuthor,
reason: String::from("bad shape"),
evidence: None,
};
let sexpr = entry.to_sexpr();
let s = alloc::format!("{}", sexpr);
assert!(s.contains("dialect-author"));
assert!(!s.contains(":evidence"));
}
#[test]
fn from_shape_violation_blames_sender() {
let sv = ShapeViolation {
rule: String::from("require :target string"),
field: Some(String::from(":target")),
expected: Some(String::from("string")),
found: Some(String::from("number")),
detail: String::from("parameter :target expected type string, found number"),
};
let evidence = list(vec![sym("propose"), kw("target"), num(42)]);
let err = ViolationError::from_shape_violation(
&sv,
Some(String::from("abc123")),
Some(String::from("t1")),
Some(evidence),
);
assert_eq!(err.kind, ViolationKind::Shape);
assert_eq!(err.message_hash, Some(String::from("abc123")));
assert_eq!(err.thread_id, Some(String::from("t1")));
assert_eq!(err.blame_chain.len(), 1);
assert_eq!(err.blame_chain[0].party, BlameParty::Sender);
assert!(err.blame_chain[0].evidence.is_some());
assert!(err.detail.contains("shape violation"));
}
#[test]
fn from_causal_violation_blames_sender() {
let cv = CausalViolation::MissingCausedBy;
let err = ViolationError::from_causal_violation(
&cv,
Some(String::from("def456")),
Some(String::from("t2")),
);
assert_eq!(err.kind, ViolationKind::Causal);
assert_eq!(err.blame_chain.len(), 1);
assert_eq!(err.blame_chain[0].party, BlameParty::Sender);
assert!(err.detail.contains("caused-by"));
}
#[test]
fn from_causal_violation_unknown_predecessor() {
let cv = CausalViolation::UnknownPredecessor {
caused_by: String::from("hash999"),
};
let err = ViolationError::from_causal_violation(&cv, None, None);
assert_eq!(err.kind, ViolationKind::Causal);
assert!(err.detail.contains("hash999"));
}
#[test]
fn from_causal_violation_invalid_predecessor() {
let cv = CausalViolation::InvalidPredecessor {
caused_by: String::from("hash111"),
expected: alloc::vec![String::from("ask"), String::from("tell")],
found: String::from("reply"),
};
let err = ViolationError::from_causal_violation(&cv, None, None);
assert!(err.detail.contains("hash111"));
assert!(err.detail.contains("reply"));
}
#[test]
fn from_r5_violation_blames_author_and_installer() {
let violations = alloc::vec![
String::from("shape targets unknown performative 'foo'"),
String::from("cycle detected: a → b → a"),
];
let err = ViolationError::from_r5_violation("bad-dialect", &violations);
assert_eq!(err.kind, ViolationKind::R5);
assert_eq!(err.blame_chain.len(), 2);
assert_eq!(err.blame_chain[0].party, BlameParty::DialectAuthor);
assert_eq!(err.blame_chain[1].party, BlameParty::Installer);
assert!(err.detail.contains("bad-dialect"));
assert!(err.detail.contains("2 R5 violation(s)"));
}
#[test]
fn from_unsatisfiable_shape_blames_dialect_author() {
let err = ViolationError::from_unsatisfiable_shape(
"logistics",
"require :route string AND require :route number",
"no value can satisfy both type constraints simultaneously",
);
assert_eq!(err.kind, ViolationKind::Shape);
assert_eq!(err.blame_chain.len(), 1);
assert_eq!(err.blame_chain[0].party, BlameParty::DialectAuthor);
assert!(err.blame_chain[0].evidence.is_none());
assert!(err.detail.contains("logistics"));
assert!(err.detail.contains("unsatisfiable"));
assert!(err.message_hash.is_none());
assert!(err.thread_id.is_none());
}
#[test]
fn to_sexpr_shape_violation() {
let sv = ShapeViolation {
rule: String::from("require :pkg string"),
field: Some(String::from(":pkg")),
expected: Some(String::from("string")),
found: Some(String::from("number")),
detail: String::from(":pkg expected string, found number"),
};
let err = ViolationError::from_shape_violation(
&sv,
Some(String::from("h1")),
Some(String::from("t1")),
Some(num(42)),
);
let sexpr = err.to_sexpr();
let s = alloc::format!("{}", sexpr);
assert!(s.starts_with("(error @unknown \"shape-violation\""));
assert!(s.contains(":detail"));
assert!(s.contains(":message-hash"));
assert!(s.contains("\"h1\""));
assert!(!s.contains(":thread"));
assert!(s.contains(":blame-chain"));
assert!(s.contains("(blame "));
assert!(s.contains(":rule"));
assert!(s.contains(":expected"));
assert!(s.contains(":found"));
}
#[test]
fn to_sexpr_without_optional_fields() {
let cv = CausalViolation::MissingCausedBy;
let err = ViolationError::from_causal_violation(&cv, None, None);
let sexpr = err.to_sexpr();
let s = alloc::format!("{}", sexpr);
assert!(s.starts_with("(error @unknown \"causal-violation\""));
assert!(!s.contains(":message-hash"));
assert!(!s.contains(":thread"));
assert!(!s.contains(":kind"));
}
#[test]
fn to_sexpr_r5_violation() {
let err = ViolationError::from_r5_violation("test-d", &[String::from("cycle found")]);
let sexpr = err.to_sexpr();
let s = alloc::format!("{}", sexpr);
assert!(s.starts_with("(error "));
assert!(s.contains("r5"));
assert!(s.contains(":blame-chain"));
let blame_count = s.matches("(blame ").count();
assert_eq!(blame_count, 2);
}
#[test]
fn to_sexpr_matches_req233_abnf() {
let sv = ShapeViolation {
rule: String::from("require :route string"),
field: Some(String::from(":route")),
expected: Some(String::from("string")),
found: Some(String::from("number")),
detail: String::from(":route expected string, found number"),
};
let err =
ViolationError::from_shape_violation(&sv, Some(String::from("f1220msg")), None, None)
.with_recipient("@sender")
.with_verifier("@receiver")
.with_dialect_context(
"logistics",
Some("@consortium"),
Some("f1220abc"),
Some("track-shipment"),
);
let s = alloc::format!("{}", err.to_sexpr());
assert!(s.starts_with("(error @sender \"shape-violation\""));
assert!(s.contains(":dialect "), "missing :dialect");
assert!(s.contains(":dialect-author "), "missing :dialect-author");
assert!(s.contains(":dialect-hash "), "missing :dialect-hash");
assert!(s.contains(":performative "), "missing :performative");
assert!(s.contains(":rule "), "missing :rule");
assert!(s.contains(":field "), "missing :field");
assert!(s.contains(":expected "), "missing :expected");
assert!(s.contains(":found "), "missing :found");
assert!(s.contains(":blamed sender"), "missing :blamed positional");
assert!(s.contains(":verifier "), "missing :verifier");
assert!(s.contains(":message-hash "), "missing :message-hash");
assert!(!s.contains(":kind"), "spec form has no :kind keyword");
assert!(!s.contains(":thread"), "spec form has no :thread keyword");
}
#[test]
fn to_sexpr_causal_includes_caused_by() {
let cv = CausalViolation::UnknownPredecessor {
caused_by: String::from("f1220pred"),
};
let err = ViolationError::from_causal_violation(&cv, None, None)
.with_recipient("@sender")
.with_dialect_context("d", None, None, Some("ack"));
let s = alloc::format!("{}", err.to_sexpr());
assert!(s.starts_with("(error @sender \"causal-violation\""));
assert!(s.contains(":caused-by"));
assert!(s.contains("\"f1220pred\""));
assert!(s.contains(":blamed sender"));
}
#[test]
fn to_sexpr_causal_invalid_predecessor_includes_caused_by() {
let cv = CausalViolation::InvalidPredecessor {
caused_by: String::from("f1220bad"),
expected: alloc::vec![String::from("pause")],
found: String::from("ack"),
};
let err = ViolationError::from_causal_violation(&cv, None, None);
assert_eq!(err.caused_by.as_deref(), Some("f1220bad"));
let s = alloc::format!("{}", err.to_sexpr());
assert!(s.contains(":caused-by"));
assert!(s.contains("\"f1220bad\""));
}
#[test]
fn to_sexpr_unsatisfiable_shape_blames_dialect_author() {
let err = ViolationError::from_unsatisfiable_shape(
"logistics",
"string AND number",
"no value satisfies both",
);
let s = alloc::format!("{}", err.to_sexpr());
assert!(s.starts_with("(error @unknown \"shape-violation\""));
assert!(s.contains(":blamed dialect-author"));
assert!(s.contains(":dialect "));
assert!(s.contains("\"logistics\""));
}
#[test]
fn to_sexpr_r5_violation_matches_abnf() {
let err = ViolationError::from_r5_violation(
"broken",
&alloc::vec![String::from("cycle: a → b → a")],
)
.with_recipient("@installer");
let s = alloc::format!("{}", err.to_sexpr());
assert!(s.starts_with("(error @installer \"r5-violation\""));
assert!(s.contains(":dialect "));
assert!(s.contains("\"broken\""));
assert!(s.contains(":blamed dialect-author"));
assert_eq!(s.matches("(blame ").count(), 2);
}
#[test]
fn to_sexpr_field_emits_keyword_atom() {
let sv = ShapeViolation {
rule: String::from("require :route string"),
field: Some(String::from(":route")),
expected: None,
found: None,
detail: String::from("test"),
};
let err = ViolationError::from_shape_violation(&sv, None, None, None);
let sexpr = err.to_sexpr();
let items = match sexpr {
SExpr::List(items) => items,
_ => panic!("error must be a list"),
};
let mut idx = None;
for (i, item) in items.iter().enumerate() {
if matches!(item, SExpr::Atom(Atom::Keyword(k)) if k == "field") {
idx = Some(i);
break;
}
}
let i = idx.expect(":field keyword must be present");
let value = &items[i + 1];
match value {
SExpr::Atom(Atom::Keyword(k)) => assert_eq!(k, "route"),
other => panic!(":field value must be a Keyword atom, got {other:?}"),
}
}
#[test]
fn with_recipient_sets_recipient() {
let cv = CausalViolation::MissingCausedBy;
let err = ViolationError::from_causal_violation(&cv, None, None).with_recipient("@alice");
assert_eq!(err.recipient.as_deref(), Some("@alice"));
}
#[test]
fn with_verifier_sets_verifier() {
let cv = CausalViolation::MissingCausedBy;
let err = ViolationError::from_causal_violation(&cv, None, None).with_verifier("@bob");
assert_eq!(err.verifier.as_deref(), Some("@bob"));
}
#[test]
fn with_message_hash_sets_message_hash() {
let cv = CausalViolation::MissingCausedBy;
let err =
ViolationError::from_causal_violation(&cv, None, None).with_message_hash("f1220msg");
assert_eq!(err.message_hash.as_deref(), Some("f1220msg"));
}
#[test]
fn with_thread_id_sets_thread_id_but_does_not_emit() {
let cv = CausalViolation::MissingCausedBy;
let err = ViolationError::from_causal_violation(&cv, None, None).with_thread_id("t-7");
assert_eq!(err.thread_id.as_deref(), Some("t-7"));
let s = alloc::format!("{}", err.to_sexpr());
assert!(!s.contains(":thread"));
assert!(!s.contains("t-7"));
}
#[test]
fn with_dialect_context_sets_all_fields() {
let cv = CausalViolation::MissingCausedBy;
let err = ViolationError::from_causal_violation(&cv, None, None).with_dialect_context(
"d",
Some("@a"),
Some("h"),
Some("p"),
);
assert_eq!(err.dialect.as_deref(), Some("d"));
assert_eq!(err.dialect_author.as_deref(), Some("@a"));
assert_eq!(err.dialect_hash.as_deref(), Some("h"));
assert_eq!(err.performative.as_deref(), Some("p"));
}
#[test]
fn with_dialect_context_handles_optional_fields() {
let cv = CausalViolation::MissingCausedBy;
let err = ViolationError::from_causal_violation(&cv, None, None)
.with_dialect_context("d", None, None, None);
assert_eq!(err.dialect.as_deref(), Some("d"));
assert_eq!(err.dialect_author, None);
assert_eq!(err.dialect_hash, None);
assert_eq!(err.performative, None);
}
#[test]
fn violation_error_display() {
let cv = CausalViolation::MissingCausedBy;
let err = ViolationError::from_causal_violation(&cv, None, None);
let s = err.to_string();
assert!(s.contains("causal violation"));
}
#[test]
fn verify_blame_shape_with_valid_evidence() {
use crate::shape::{ShapeConstraint, ShapeRule, TypeConstraint};
let constraint = ShapeConstraint {
performative: String::from("track"),
rules: vec![ShapeRule::Require {
keyword: String::from("package"),
type_constraint: Some(TypeConstraint::String),
children: vec![],
}],
};
let evidence = list(vec![sym("track"), kw("package"), num(42)]);
let sv = ShapeViolation {
rule: String::from("require :package string"),
field: Some(String::from(":package")),
expected: Some(String::from("string")),
found: Some(String::from("number")),
detail: String::from(":package expected string, found number"),
};
let err = ViolationError::from_shape_violation(&sv, None, None, Some(evidence));
assert!(err.verify_blame(Some(&constraint)));
}
#[test]
fn verify_blame_shape_with_passing_evidence_returns_false() {
use crate::shape::{ShapeConstraint, ShapeRule, TypeConstraint};
let constraint = ShapeConstraint {
performative: String::from("track"),
rules: vec![ShapeRule::Require {
keyword: String::from("package"),
type_constraint: Some(TypeConstraint::String),
children: vec![],
}],
};
let evidence = list(vec![sym("track"), kw("package"), str_expr("box-1")]);
let sv = ShapeViolation {
rule: String::from("require :package string"),
field: Some(String::from(":package")),
expected: Some(String::from("string")),
found: Some(String::from("number")),
detail: String::from("fabricated violation"),
};
let err = ViolationError::from_shape_violation(&sv, None, None, Some(evidence));
assert!(!err.verify_blame(Some(&constraint)));
}
#[test]
fn verify_blame_shape_without_constraint_returns_false() {
let sv = ShapeViolation {
rule: String::from("require :x"),
field: None,
expected: None,
found: None,
detail: String::from("missing"),
};
let err = ViolationError::from_shape_violation(&sv, None, None, Some(sym("x")));
assert!(!err.verify_blame(None));
}
#[test]
fn verify_blame_shape_without_evidence_returns_false() {
use crate::shape::{ShapeConstraint, ShapeRule, TypeConstraint};
let constraint = ShapeConstraint {
performative: String::from("track"),
rules: vec![ShapeRule::Require {
keyword: String::from("package"),
type_constraint: Some(TypeConstraint::String),
children: vec![],
}],
};
let sv = ShapeViolation {
rule: String::from("require :package string"),
field: None,
expected: None,
found: None,
detail: String::from("missing"),
};
let err = ViolationError::from_shape_violation(&sv, None, None, None);
assert!(!err.verify_blame(Some(&constraint)));
}
#[test]
fn verify_blame_causal() {
let cv = CausalViolation::MissingCausedBy;
let err = ViolationError::from_causal_violation(&cv, None, None);
assert!(err.verify_blame(None));
}
#[test]
fn verify_blame_r5() {
let err = ViolationError::from_r5_violation("d", &[String::from("bad")]);
assert!(err.verify_blame(None));
}
#[test]
fn verify_blame_r5_without_author_returns_false() {
let mut err = ViolationError::from_r5_violation("d", &[String::from("x")]);
err.blame_chain = vec![BlameEntry {
party: BlameParty::Installer,
reason: String::from("installed bad dialect"),
evidence: None,
}];
assert!(!err.verify_blame(None));
}
#[test]
fn verify_blame_causal_without_sender_returns_false() {
let cv = CausalViolation::MissingCausedBy;
let mut err = ViolationError::from_causal_violation(&cv, None, None);
err.blame_chain = vec![BlameEntry {
party: BlameParty::DialectAuthor,
reason: String::from("wrong party"),
evidence: None,
}];
assert!(!err.verify_blame(None));
}
#[test]
fn blame_party_copy_and_eq() {
let a = BlameParty::Sender;
let b = a; assert_eq!(a, b);
}
#[test]
fn violation_error_clone_and_eq() {
let err = ViolationError::from_r5_violation("d", &[String::from("x")]);
let err2 = err.clone();
assert_eq!(err, err2);
}
#[test]
fn record_metrics_does_not_panic_shape() {
let sv = ShapeViolation {
rule: String::from("require :x string"),
field: Some(String::from(":x")),
expected: Some(String::from("string")),
found: Some(String::from("number")),
detail: String::from(":x expected string, found number"),
};
let err = ViolationError::from_shape_violation(
&sv,
Some(String::from("h1")),
Some(String::from("t1")),
Some(num(42)),
);
err.record_metrics("test-dialect");
}
#[test]
fn record_metrics_does_not_panic_causal() {
let cv = CausalViolation::MissingCausedBy;
let err = ViolationError::from_causal_violation(&cv, None, None);
err.record_metrics("test-dialect");
}
#[test]
fn record_metrics_does_not_panic_r5() {
let err = ViolationError::from_r5_violation("bad-d", &[String::from("cycle")]);
err.record_metrics("bad-d");
}
}