#![forbid(unsafe_code)]
use crate::parser::{self, ParseError};
use alloc::string::String;
use alloc::vec::Vec;
use cbcl_core::blame::ViolationError;
use cbcl_core::dialect::{Dialect, DialectRegistry};
use cbcl_core::evaluator::{evaluate_without_shape_check, EvalError};
use cbcl_core::message::Message;
use cbcl_core::policy::{apply_policy, PendingReason, PolicyOutcome, UnknownPredecessorPolicy};
use cbcl_core::protocol::CausalViolation;
use cbcl_core::r1;
use cbcl_core::r3;
use cbcl_core::r5;
use cbcl_core::sexpr::SExpr;
use cbcl_core::shape::ShapeViolation;
use cbcl_core::store::{MessageStore, ThreadId};
use core::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationError {
R1RecursivePerformative {
performatives: Vec<String>,
},
R2ResourceBoundsInvalid {
field: &'static str,
value: u32,
},
R2FuelExhausted,
R3CoreOverride {
performatives: Vec<String>,
},
R4SignatureInvalid,
R5Violation {
errors: Vec<String>,
},
CausalViolation {
violation: CausalViolation,
blame: ViolationError,
},
ShapeViolation {
violation: ShapeViolation,
blame: ViolationError,
},
MalformedMessage {
reason: String,
},
MalformedDialect {
reason: String,
},
}
impl fmt::Display for ValidationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ValidationError::R1RecursivePerformative { performatives } => {
write!(
f,
"R1 violation: recursive performative(s): {}",
performatives.join(", ")
)
}
ValidationError::R2ResourceBoundsInvalid { field, value } => {
write!(f, "R2 violation: invalid resource bound {field}={value}")
}
ValidationError::R2FuelExhausted => write!(f, "R2 violation: fuel exhausted"),
ValidationError::R3CoreOverride { performatives } => {
write!(
f,
"R3 violation: core performative(s) overridden: {}",
performatives.join(", ")
)
}
ValidationError::R4SignatureInvalid => write!(f, "R4 violation: invalid signature"),
ValidationError::R5Violation { errors } => {
write!(f, "R5 violation: {}", errors.join("; "))
}
ValidationError::CausalViolation { blame, .. } => {
write!(f, "causal violation: {}", blame)
}
ValidationError::ShapeViolation { blame, .. } => {
write!(f, "shape violation: {}", blame)
}
ValidationError::MalformedMessage { reason } => {
write!(f, "malformed message: {reason}")
}
ValidationError::MalformedDialect { reason } => {
write!(f, "malformed dialect: {reason}")
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for ValidationError {}
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(clippy::large_enum_variant)]
pub enum PipelineResult {
Success(Message),
ParseError(ParseError),
ValidationError(ValidationError),
Pending {
message: Message,
reason: PendingReason,
},
Buffered {
message: Message,
},
}
pub struct PipelineContext<'a, S: MessageStore> {
pub registry: &'a DialectRegistry,
pub store: &'a S,
pub policy: UnknownPredecessorPolicy,
}
impl<'a, S: MessageStore> PipelineContext<'a, S> {
pub fn new(registry: &'a DialectRegistry, store: &'a S) -> Self {
Self {
registry,
store,
policy: UnknownPredecessorPolicy::default(),
}
}
pub fn with_policy(
registry: &'a DialectRegistry,
store: &'a S,
policy: UnknownPredecessorPolicy,
) -> Self {
Self {
registry,
store,
policy,
}
}
}
pub fn run_pipeline(input: &str) -> PipelineResult {
let sexpr = match parser::parse(input) {
Ok(e) => e,
Err(e) => return PipelineResult::ParseError(e),
};
let message = match crate::message_parser::parse_message(&sexpr) {
Ok(m) => m,
Err(reason) => {
return PipelineResult::ValidationError(ValidationError::MalformedMessage { reason })
}
};
if let Err(err) = validate_meta_dialect(&message, None) {
return PipelineResult::ValidationError(err);
}
PipelineResult::Success(message)
}
pub fn run_pipeline_full<S: MessageStore>(
input: &str,
ctx: &PipelineContext<'_, S>,
) -> PipelineResult {
let sexpr = match parser::parse(input) {
Ok(e) => e,
Err(e) => return PipelineResult::ParseError(e),
};
let message = match crate::message_parser::parse_message(&sexpr) {
Ok(m) => m,
Err(reason) => {
return PipelineResult::ValidationError(ValidationError::MalformedMessage { reason })
}
};
if let Err(err) = validate_meta_dialect(&message, Some(ctx.registry)) {
return PipelineResult::ValidationError(err);
}
let inner_simple = message.innermost_simple();
if let Some(Message::Simple {
caused_by,
thread,
performative,
..
}) = inner_simple
{
let performative = Some(performative);
if let Some(perf) = performative {
let perf_name = perf.name();
let thread_id = ThreadId(thread.clone().unwrap_or_else(|| String::from("default")));
for d in ctx.registry.iter() {
let Some(ref proto) = d.causal_protocol else {
continue;
};
if !proto.steps.contains_key(perf_name) {
continue;
}
let result = cbcl_core::protocol::verify_causal(
perf_name,
caused_by.as_ref(),
ctx.store,
proto,
&thread_id,
);
match apply_policy(&result, &ctx.policy) {
PolicyOutcome::Accept => {}
PolicyOutcome::Reject(cv) => {
let blame =
ViolationError::from_causal_violation(&cv, None, thread.clone())
.with_dialect_context(
&d.name,
d.author.as_deref(),
d.hash.as_deref(),
Some(perf_name),
);
blame.record_metrics(&d.name);
return PipelineResult::ValidationError(ValidationError::CausalViolation {
violation: cv,
blame,
});
}
PolicyOutcome::Pending(reason) => {
return PipelineResult::Pending { message, reason };
}
PolicyOutcome::Buffered => {
return PipelineResult::Buffered { message };
}
}
}
}
let eval_result = match evaluate_without_shape_check(&message, ctx.registry) {
Ok(r) => r,
Err(eval_err) => {
return PipelineResult::ValidationError(eval_error_to_validation(
eval_err,
thread.clone(),
))
}
};
if let Some(perf) = performative {
let perf_name = perf.name();
for dialect in ctx.registry.iter() {
for shape in &dialect.shapes {
if shape.performative == perf_name {
if let Err(sv) = shape.check(&eval_result.expanded) {
let blame = ViolationError::from_shape_violation(
&sv,
None,
thread.clone(),
None,
)
.with_dialect_context(
&dialect.name,
dialect.author.as_deref(),
dialect.hash.as_deref(),
Some(perf_name),
);
blame.record_metrics(&dialect.name);
return PipelineResult::ValidationError(
ValidationError::ShapeViolation {
violation: sv,
blame,
},
);
}
}
}
}
}
}
PipelineResult::Success(message)
}
#[allow(clippy::result_large_err)]
fn validate_meta_dialect(
message: &Message,
registry: Option<&DialectRegistry>,
) -> Result<(), ValidationError> {
if let Message::Meta { ref dialect_def } = message {
if let SExpr::List(items) = dialect_def {
if items.is_empty() {
return Ok(());
}
if items[0].is_symbol("define") {
return validate_define_dialect(dialect_def, registry);
}
if items[0].is_symbol("teach") {
for item in items.iter().skip(1) {
if let SExpr::List(inner_items) = item {
if !inner_items.is_empty() && inner_items[0].is_symbol("define") {
return validate_define_dialect(item, registry);
}
}
}
}
}
}
Ok(())
}
#[allow(clippy::result_large_err)]
fn validate_define_dialect(
dialect_def: &SExpr,
registry: Option<&DialectRegistry>,
) -> Result<(), ValidationError> {
let dialect = crate::dialect_parser::parse_dialect(dialect_def)
.map_err(|reason| ValidationError::MalformedDialect { reason })?;
let recursive = r1::r1_violations(&dialect);
if !recursive.is_empty() {
return Err(ValidationError::R1RecursivePerformative {
performatives: recursive,
});
}
if let Some((field, value)) = invalid_resource_bound(&dialect) {
return Err(ValidationError::R2ResourceBoundsInvalid { field, value });
}
let overrides = r3::r3_violations(&dialect);
if !overrides.is_empty() {
return Err(ValidationError::R3CoreOverride {
performatives: overrides,
});
}
let base = cbcl_core::dialect::base_dialect();
let mut ancestors: alloc::vec::Vec<&cbcl_core::dialect::Dialect> = alloc::vec![];
let mut credited_base = false;
if let Some(reg) = registry {
for name in &dialect.extends {
let resolved = if name == "cbcl" {
"cbcl-base"
} else {
name.as_str()
};
if let Some(parent) = reg.find_by_name(resolved) {
ancestors.push(parent);
if resolved == base.name {
credited_base = true;
}
}
}
}
if !credited_base {
let extends_base = dialect
.extends
.iter()
.any(|name| name == "cbcl" || name == &base.name);
if extends_base {
ancestors.push(&base);
}
}
let r5_errors = r5::r5_violations_with_ancestors(&dialect, &ancestors);
if !r5_errors.is_empty() {
return Err(ValidationError::R5Violation { errors: r5_errors });
}
Ok(())
}
fn invalid_resource_bound(dialect: &Dialect) -> Option<(&'static str, u32)> {
let bounds = &dialect.resources;
if bounds.max_depth == 0 || bounds.max_depth > 64 {
return Some(("max_depth", bounds.max_depth));
}
if bounds.max_expansion_size == 0 || bounds.max_expansion_size > 8192 {
return Some(("max_expansion_size", bounds.max_expansion_size));
}
None
}
fn eval_error_to_validation(err: EvalError, thread: Option<String>) -> ValidationError {
match err {
EvalError::UnknownPerformative(name) => ValidationError::MalformedMessage {
reason: alloc::format!("unknown performative: {name}"),
},
EvalError::UnscopedDialectPerformative(name) => ValidationError::MalformedMessage {
reason: alloc::format!(
"dialect performative '{name}' invoked outside (lang <dialect> ...); \
the message must name the dialect that defines it"
),
},
EvalError::TemplateExpansionFailed { performative: _ } => ValidationError::R2FuelExhausted,
EvalError::UnknownDialect(name) => ValidationError::MalformedMessage {
reason: alloc::format!("unknown dialect: {name}"),
},
EvalError::MalformedMessage(reason) => ValidationError::MalformedMessage { reason },
EvalError::ShapeViolation(sv) => {
let blame = ViolationError::from_shape_violation(&sv, None, thread, None);
ValidationError::ShapeViolation {
violation: sv,
blame,
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::collections::BTreeMap;
use cbcl_core::dialect::{DialectRegistry, PerformativeDef, ResourceBounds};
use cbcl_core::message::{CausedBy, MessageType, Performative};
use cbcl_core::protocol::{CausalProtocol, NodeRef, StepDecl};
use cbcl_core::sexpr::Atom;
use cbcl_core::shape::{ShapeConstraint, ShapeRule, TypeConstraint};
use cbcl_core::store::{ContentHash, ThreadId, ThreadedMessageStore};
fn effect_template(action: &str) -> SExpr {
SExpr::List(alloc::vec![
SExpr::Atom(Atom::Symbol(String::from("effect"))),
SExpr::Atom(Atom::Symbol(String::from(action))),
])
}
fn make_simple_msg(perf: &str, caused_by: Option<CausedBy>) -> Message {
Message::Simple {
performative: Performative::Custom(String::from(perf)),
recipient: None,
content: SExpr::Atom(Atom::Str(String::from("test"))),
params: alloc::vec![],
thread: None,
sender: None,
caused_by,
}
}
#[test]
fn pipeline_parse_error() {
let result = run_pipeline("(unclosed");
assert!(matches!(result, PipelineResult::ParseError(_)));
}
#[test]
fn pipeline_simple_message() {
let result = run_pipeline("(tell \"hello\")");
assert!(matches!(result, PipelineResult::Success(_)));
if let PipelineResult::Success(msg) = result {
assert_eq!(msg.message_type(), MessageType::Simple);
}
}
#[test]
fn pipeline_meta_define() {
let input = "(meta (define test-dialect (cbcl) @author))";
let result = run_pipeline(input);
assert!(matches!(result, PipelineResult::Success(_)));
if let PipelineResult::Success(msg) = result {
assert_eq!(msg.message_type(), MessageType::Meta);
}
}
#[test]
fn pipeline_malformed_dialect() {
let input = "(meta (define))"; let result = run_pipeline(input);
assert!(matches!(
result,
PipelineResult::ValidationError(ValidationError::MalformedDialect { .. })
));
}
#[test]
fn pipeline_custom_performative() {
let result = run_pipeline(
"(lang cbcl-planning (share-conditional pickup box-location box-in-hand))",
);
assert!(matches!(result, PipelineResult::Success(_)));
}
#[test]
fn pipeline_meta_query() {
let result = run_pipeline("(meta (query (speak? cbcl-planning)))");
assert!(matches!(result, PipelineResult::Success(_)));
}
#[test]
fn pipeline_rejects_r3_core_override() {
let result = run_pipeline("(meta (define bad (cbcl) @author (extend tell () x)))");
assert!(matches!(
result,
PipelineResult::ValidationError(ValidationError::R3CoreOverride { .. })
));
}
#[test]
fn pipeline_rejects_mutual_recursion() {
let result = run_pipeline(
"(meta (define cyclic (cbcl) @author (extend ping () (pong)) (extend pong () (ping))))",
);
assert!(matches!(
result,
PipelineResult::ValidationError(ValidationError::R1RecursivePerformative { .. })
));
}
#[test]
fn pipeline_teach_validates_r3() {
let result =
run_pipeline("(meta (teach @bob (define bad (cbcl) @author (extend tell () x))))");
assert!(matches!(
result,
PipelineResult::ValidationError(ValidationError::R3CoreOverride { .. })
));
}
#[test]
fn pipeline_teach_valid_passes() {
let result = run_pipeline("(meta (teach @bob (define good-dialect (cbcl) @author)))");
assert!(matches!(result, PipelineResult::Success(_)));
}
#[test]
fn full_pipeline_simple_message_passes() {
let registry = DialectRegistry::new();
let store = ThreadedMessageStore::new();
let ctx = PipelineContext::new(®istry, &store);
let result = run_pipeline_full("(tell \"hello\")", &ctx);
assert!(matches!(result, PipelineResult::Success(_)));
}
#[test]
fn full_pipeline_rejects_causal_violation() {
let mut registry = DialectRegistry::new();
let mut steps = BTreeMap::new();
steps.insert(
"begin".into(),
StepDecl {
performative: "begin".into(),
predecessors: alloc::vec![],
successors: alloc::vec![NodeRef::Single("greet".into())],
},
);
steps.insert(
"greet".into(),
StepDecl {
performative: "greet".into(),
predecessors: alloc::vec![NodeRef::Single("begin".into())],
successors: alloc::vec![],
},
);
let proto = CausalProtocol { steps };
registry
.install(cbcl_core::dialect::Dialect {
types: Default::default(),
roles: Vec::new(),
state: None,
state_bounds: None,
causal_locality: Default::default(),
name: String::from("proto-dialect"),
extends: alloc::vec![String::from("cbcl")],
author: None,
performatives: alloc::vec![PerformativeDef {
role: None,
name: String::from("greet"),
params: alloc::vec![],
template: effect_template("greet-action"),
}],
resources: ResourceBounds {
max_depth: 8,
max_expansion_size: 512,
},
examples: alloc::vec![],
signature: None,
hash: None,
protocol: None,
causal_protocol: Some(proto),
shapes: alloc::vec![],
})
.unwrap();
let store = ThreadedMessageStore::new();
let ctx = PipelineContext::new(®istry, &store);
let result = run_pipeline_full("(lang proto-dialect (greet \"hi\"))", &ctx);
assert!(
matches!(
result,
PipelineResult::ValidationError(ValidationError::CausalViolation { .. })
),
"expected causal violation, got {:?}",
result
);
}
#[test]
fn full_pipeline_shape_violation_rejected() {
let mut registry = DialectRegistry::new();
registry
.install(cbcl_core::dialect::Dialect {
types: Default::default(),
roles: Vec::new(),
state: None,
state_bounds: None,
causal_locality: Default::default(),
name: String::from("shape-dialect"),
extends: alloc::vec![String::from("cbcl")],
author: None,
performatives: alloc::vec![PerformativeDef {
role: None,
name: String::from("propose"),
params: alloc::vec![],
template: effect_template("propose-action"),
}],
resources: ResourceBounds {
max_depth: 8,
max_expansion_size: 512,
},
examples: alloc::vec![],
signature: None,
hash: None,
protocol: None,
causal_protocol: None,
shapes: alloc::vec![ShapeConstraint {
performative: String::from("propose"),
rules: alloc::vec![ShapeRule::Require {
keyword: String::from("target"),
type_constraint: Some(TypeConstraint::String),
children: alloc::vec![],
}],
}],
})
.unwrap();
let store = ThreadedMessageStore::new();
let ctx = PipelineContext::new(®istry, &store);
let result = run_pipeline_full("(lang shape-dialect (propose \"idea\"))", &ctx);
assert!(
matches!(
result,
PipelineResult::ValidationError(ValidationError::ShapeViolation { .. })
),
"expected shape violation, got {:?}",
result
);
}
#[test]
fn full_pipeline_causal_valid_with_predecessor() {
let mut registry = DialectRegistry::new();
let mut steps = BTreeMap::new();
steps.insert(
"begin".into(),
StepDecl {
performative: "begin".into(),
predecessors: alloc::vec![],
successors: alloc::vec![NodeRef::Single("ack".into())],
},
);
steps.insert(
"ack".into(),
StepDecl {
performative: "ack".into(),
predecessors: alloc::vec![NodeRef::Single("begin".into())],
successors: alloc::vec![],
},
);
let proto = CausalProtocol { steps };
registry
.install(cbcl_core::dialect::Dialect {
types: Default::default(),
roles: Vec::new(),
state: None,
state_bounds: None,
causal_locality: Default::default(),
name: String::from("ack-dialect"),
extends: alloc::vec![String::from("cbcl")],
author: None,
performatives: alloc::vec![PerformativeDef {
role: None,
name: String::from("ack"),
params: alloc::vec![],
template: effect_template("ack-action"),
}],
resources: ResourceBounds {
max_depth: 8,
max_expansion_size: 512,
},
examples: alloc::vec![],
signature: None,
hash: None,
protocol: None,
causal_protocol: Some(proto),
shapes: alloc::vec![],
})
.unwrap();
let thread = ThreadId(String::from("default"));
let mut store = ThreadedMessageStore::new();
store.append(
ContentHash(String::from("abc123")),
thread.clone(),
make_simple_msg("begin", Some(CausedBy::Begin)),
);
let ctx = PipelineContext::new(®istry, &store);
let result = run_pipeline_full(
"(lang ack-dialect (ack \"done\" :caused-by \"abc123\"))",
&ctx,
);
assert!(
matches!(result, PipelineResult::Success(_)),
"expected success, got {:?}",
result
);
}
#[test]
fn full_pipeline_meta_define_still_validated() {
let registry = DialectRegistry::new();
let store = ThreadedMessageStore::new();
let ctx = PipelineContext::new(®istry, &store);
let result = run_pipeline_full(
"(meta (define bad (cbcl) @author (extend tell () x)))",
&ctx,
);
assert!(matches!(
result,
PipelineResult::ValidationError(ValidationError::R3CoreOverride { .. })
));
}
#[test]
fn full_pipeline_teach_validated() {
let registry = DialectRegistry::new();
let store = ThreadedMessageStore::new();
let ctx = PipelineContext::new(®istry, &store);
let result = run_pipeline_full(
"(meta (teach @bob (define bad (cbcl) @author (extend tell () x))))",
&ctx,
);
assert!(matches!(
result,
PipelineResult::ValidationError(ValidationError::R3CoreOverride { .. })
));
}
fn ack_dialect_registry() -> DialectRegistry {
let mut registry = DialectRegistry::new();
let mut steps = BTreeMap::new();
steps.insert(
"begin".into(),
StepDecl {
performative: "begin".into(),
predecessors: alloc::vec![],
successors: alloc::vec![NodeRef::Single("ack".into())],
},
);
steps.insert(
"ack".into(),
StepDecl {
performative: "ack".into(),
predecessors: alloc::vec![NodeRef::Single("begin".into())],
successors: alloc::vec![],
},
);
let proto = CausalProtocol { steps };
registry
.install(cbcl_core::dialect::Dialect {
types: Default::default(),
roles: Vec::new(),
state: None,
state_bounds: None,
causal_locality: Default::default(),
name: String::from("ack-dialect"),
extends: alloc::vec![String::from("cbcl")],
author: None,
performatives: alloc::vec![PerformativeDef {
role: None,
name: String::from("ack"),
params: alloc::vec![],
template: effect_template("ack-action"),
}],
resources: ResourceBounds {
max_depth: 8,
max_expansion_size: 512,
},
examples: alloc::vec![],
signature: None,
hash: None,
protocol: None,
causal_protocol: Some(proto),
shapes: alloc::vec![],
})
.unwrap();
registry
}
#[test]
fn full_pipeline_unknown_predecessor_rejects_under_default_policy() {
let registry = ack_dialect_registry();
let store = ThreadedMessageStore::new(); let ctx = PipelineContext::new(®istry, &store);
let result = run_pipeline_full(
"(lang ack-dialect (ack \"done\" :caused-by \"missing-hash\"))",
&ctx,
);
assert!(
matches!(
result,
PipelineResult::Pending {
reason: cbcl_core::policy::PendingReason::CausalPending,
..
}
),
"expected Pending under default Reject policy, got {:?}",
result
);
}
#[test]
fn full_pipeline_unknown_predecessor_buffers_under_buffer_policy() {
let registry = ack_dialect_registry();
let store = ThreadedMessageStore::new();
let ctx = PipelineContext::with_policy(
®istry,
&store,
cbcl_core::policy::UnknownPredecessorPolicy::buffer(60),
);
let result = run_pipeline_full(
"(lang ack-dialect (ack \"done\" :caused-by \"missing-hash\"))",
&ctx,
);
assert!(
matches!(result, PipelineResult::Buffered { .. }),
"expected Buffered under Buffer policy, got {:?}",
result
);
}
#[test]
fn full_pipeline_causal_violation_takes_precedence_over_shape() {
let mut registry = DialectRegistry::new();
let mut steps = BTreeMap::new();
steps.insert(
"begin".into(),
StepDecl {
performative: "begin".into(),
predecessors: alloc::vec![],
successors: alloc::vec![NodeRef::Single("ack".into())],
},
);
steps.insert(
"ack".into(),
StepDecl {
performative: "ack".into(),
predecessors: alloc::vec![NodeRef::Single("begin".into())],
successors: alloc::vec![],
},
);
let proto = CausalProtocol { steps };
registry
.install(cbcl_core::dialect::Dialect {
types: Default::default(),
roles: Vec::new(),
state: None,
state_bounds: None,
causal_locality: Default::default(),
name: String::from("ack-with-shape"),
extends: alloc::vec![String::from("cbcl")],
author: None,
performatives: alloc::vec![PerformativeDef {
role: None,
name: String::from("ack"),
params: alloc::vec![],
template: effect_template("ack-action"),
}],
resources: ResourceBounds {
max_depth: 8,
max_expansion_size: 512,
},
examples: alloc::vec![],
signature: None,
hash: None,
protocol: None,
causal_protocol: Some(proto),
shapes: alloc::vec![ShapeConstraint {
performative: String::from("ack"),
rules: alloc::vec![ShapeRule::Require {
keyword: String::from("target"),
type_constraint: Some(TypeConstraint::String),
children: alloc::vec![],
}],
}],
})
.unwrap();
let store = ThreadedMessageStore::new();
let ctx = PipelineContext::new(®istry, &store);
let result = run_pipeline_full("(lang ack-with-shape (ack \"done\"))", &ctx);
assert!(
matches!(
result,
PipelineResult::ValidationError(ValidationError::CausalViolation { .. })
),
"expected CausalViolation to take precedence, got {:?}",
result
);
}
#[test]
fn full_pipeline_child_protocol_on_core_perf_is_enforced() {
let mut registry = DialectRegistry::new();
let mut steps = BTreeMap::new();
steps.insert(
"begin".into(),
StepDecl {
performative: "begin".into(),
predecessors: alloc::vec![],
successors: alloc::vec![NodeRef::Single("ok".into())],
},
);
steps.insert(
"ok".into(),
StepDecl {
performative: "ok".into(),
predecessors: alloc::vec![NodeRef::Single("begin".into())],
successors: alloc::vec![],
},
);
registry
.install(cbcl_core::dialect::Dialect {
types: Default::default(),
roles: Vec::new(),
state: None,
state_bounds: None,
causal_locality: Default::default(),
name: String::from("ok-protocol"),
extends: alloc::vec![String::from("cbcl")],
author: None,
performatives: alloc::vec![], resources: ResourceBounds {
max_depth: 8,
max_expansion_size: 512,
},
examples: alloc::vec![],
signature: None,
hash: None,
protocol: None,
causal_protocol: Some(CausalProtocol { steps }),
shapes: alloc::vec![],
})
.unwrap();
let store = ThreadedMessageStore::new();
let ctx = PipelineContext::new(®istry, &store);
let result = run_pipeline_full("(ok)", &ctx);
assert!(
matches!(
result,
PipelineResult::ValidationError(ValidationError::CausalViolation { .. })
),
"expected child protocol on core `ok` to fire, got {:?}",
result
);
}
#[test]
fn full_pipeline_meta_define_credits_non_base_parent_via_registry() {
let mut registry = DialectRegistry::new();
registry
.install(cbcl_core::dialect::Dialect {
types: Default::default(),
roles: Vec::new(),
state: None,
state_bounds: None,
causal_locality: Default::default(),
name: String::from("parent-dialect"),
extends: alloc::vec![String::from("cbcl")],
author: None,
performatives: alloc::vec![PerformativeDef {
role: None,
name: String::from("notify"),
params: alloc::vec![],
template: effect_template("notify-action"),
}],
resources: ResourceBounds {
max_depth: 8,
max_expansion_size: 512,
},
examples: alloc::vec![],
signature: None,
hash: None,
protocol: None,
causal_protocol: None,
shapes: alloc::vec![],
})
.unwrap();
let store = ThreadedMessageStore::new();
let ctx = PipelineContext::new(®istry, &store);
let input = "\
(meta (define child-dialect (parent-dialect) @author \
(protocol (then begin notify))))";
let result = run_pipeline_full(input, &ctx);
assert!(
matches!(result, PipelineResult::Success(_)),
"expected meta-define with registry ancestor to pass, got {:?}",
result
);
}
#[test]
fn full_pipeline_envelope_wrapping_does_not_bypass_causal() {
let registry = ack_dialect_registry();
let store = ThreadedMessageStore::new();
let ctx = PipelineContext::new(®istry, &store);
let result = run_pipeline_full(
"(envelope (:from @alice) (ack \"done\" :caused-by \"missing\"))",
&ctx,
);
assert!(
!matches!(result, PipelineResult::Success(_)),
"expected wrapper not to bypass verification, got Success: {result:?}"
);
}
#[test]
fn full_pipeline_lang_scoped_message_does_not_bypass_causal() {
let registry = ack_dialect_registry();
let store = ThreadedMessageStore::new();
let ctx = PipelineContext::new(®istry, &store);
let result = run_pipeline_full(
"(lang ack-dialect (lang ack-dialect (ack \"done\" :caused-by \"missing\")))",
&ctx,
);
assert!(
!matches!(result, PipelineResult::Success(_)),
"expected dialect-scoped wrapper not to bypass verification, got Success: {result:?}"
);
}
fn parse_install_hash(source: &str) -> String {
let sexpr = parser::parse(source).expect("dialect source parses");
let d = crate::dialect_parser::parse_dialect(&sexpr).expect("dialect extracts");
assert!(d.hash.is_none(), "source declares no :hash");
let mut registry = DialectRegistry::new();
registry.install(d).expect("dialect installs");
registry
.get(1)
.expect("installed at index 1")
.hash
.clone()
.expect("install populates hash")
}
#[test]
fn parsed_dialect_hash_populated_after_install() {
let h = parse_install_hash(
"(define greeting-dialect (cbcl) @author (extend greet () (effect greet-action)))",
);
let hex = h.strip_prefix("f1220").expect("f1220 prefix");
assert_eq!(hex.len(), 64);
assert!(hex
.chars()
.all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)));
}
#[test]
fn parsed_dialect_hash_stable_under_reformatting() {
let compact =
"(define greeting-dialect (cbcl) @author (extend greet () (effect greet-action)))";
let sprawling = "(define greeting-dialect\n (cbcl)\n @author\n (extend greet\n ()\n (effect greet-action)))\n";
assert_eq!(
parse_install_hash(compact),
parse_install_hash(sprawling),
"reformatted-but-equal source must yield the identical hash"
);
}
#[test]
fn parsed_dialect_hash_changes_when_performative_renamed() {
let original =
"(define greeting-dialect (cbcl) @author (extend greet () (effect greet-action)))";
let renamed =
"(define greeting-dialect (cbcl) @author (extend salute () (effect greet-action)))";
assert_ne!(
parse_install_hash(original),
parse_install_hash(renamed),
"renaming a performative must change the hash"
);
}
#[test]
fn blame_carries_installed_dialect_hash() {
let mut registry = DialectRegistry::new();
registry
.install(cbcl_core::dialect::Dialect {
types: Default::default(),
roles: Vec::new(),
state: None,
state_bounds: None,
causal_locality: Default::default(),
name: String::from("shape-dialect"),
extends: alloc::vec![String::from("cbcl")],
author: Some(String::from("@shape-author")),
performatives: alloc::vec![PerformativeDef {
role: None,
name: String::from("propose"),
params: alloc::vec![],
template: effect_template("propose-action"),
}],
resources: ResourceBounds {
max_depth: 8,
max_expansion_size: 512,
},
examples: alloc::vec![],
signature: None,
hash: None,
protocol: None,
causal_protocol: None,
shapes: alloc::vec![ShapeConstraint {
performative: String::from("propose"),
rules: alloc::vec![ShapeRule::Require {
keyword: String::from("target"),
type_constraint: Some(TypeConstraint::String),
children: alloc::vec![],
}],
}],
})
.unwrap();
let installed_hash = registry
.find_by_name("shape-dialect")
.unwrap()
.hash
.clone()
.expect("install populates hash");
let store = ThreadedMessageStore::new();
let ctx = PipelineContext::new(®istry, &store);
let result = run_pipeline_full("(lang shape-dialect (propose \"idea\"))", &ctx);
let PipelineResult::ValidationError(ValidationError::ShapeViolation { blame, .. }) = result
else {
panic!("expected shape violation, got {result:?}");
};
assert_eq!(blame.dialect_hash.as_deref(), Some(installed_hash.as_str()));
assert_eq!(blame.dialect.as_deref(), Some("shape-dialect"));
assert_eq!(blame.performative.as_deref(), Some("propose"));
let rendered = alloc::format!("{}", blame.to_sexpr());
assert!(
rendered.contains("dialect-hash") && rendered.contains(&installed_hash),
"blame wire form must carry the installed dialect hash: {rendered}"
);
}
}