1#![forbid(unsafe_code)]
15
16use crate::parser::{self, ParseError};
17use alloc::string::String;
18use alloc::vec::Vec;
19use cbcl_core::blame::ViolationError;
20use cbcl_core::dialect::{Dialect, DialectRegistry};
21use cbcl_core::evaluator::{evaluate_without_shape_check, EvalError};
22use cbcl_core::message::Message;
23use cbcl_core::policy::{apply_policy, PendingReason, PolicyOutcome, UnknownPredecessorPolicy};
24use cbcl_core::protocol::CausalViolation;
25use cbcl_core::r1;
26use cbcl_core::r3;
27use cbcl_core::r5;
28use cbcl_core::sexpr::SExpr;
29use cbcl_core::shape::ShapeViolation;
30use cbcl_core::store::{MessageStore, ThreadId};
31use core::fmt;
32
33#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum ValidationError {
36 R1RecursivePerformative {
37 performatives: Vec<String>,
38 },
39 R2ResourceBoundsInvalid {
40 field: &'static str,
41 value: u32,
42 },
43 R2FuelExhausted,
44 R3CoreOverride {
45 performatives: Vec<String>,
46 },
47 R4SignatureInvalid,
48 R5Violation {
50 errors: Vec<String>,
51 },
52 CausalViolation {
54 violation: CausalViolation,
55 blame: ViolationError,
56 },
57 ShapeViolation {
59 violation: ShapeViolation,
60 blame: ViolationError,
61 },
62 MalformedMessage {
63 reason: String,
64 },
65 MalformedDialect {
66 reason: String,
67 },
68}
69
70impl fmt::Display for ValidationError {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 match self {
73 ValidationError::R1RecursivePerformative { performatives } => {
74 write!(
75 f,
76 "R1 violation: recursive performative(s): {}",
77 performatives.join(", ")
78 )
79 }
80 ValidationError::R2ResourceBoundsInvalid { field, value } => {
81 write!(f, "R2 violation: invalid resource bound {field}={value}")
82 }
83 ValidationError::R2FuelExhausted => write!(f, "R2 violation: fuel exhausted"),
84 ValidationError::R3CoreOverride { performatives } => {
85 write!(
86 f,
87 "R3 violation: core performative(s) overridden: {}",
88 performatives.join(", ")
89 )
90 }
91 ValidationError::R4SignatureInvalid => write!(f, "R4 violation: invalid signature"),
92 ValidationError::R5Violation { errors } => {
93 write!(f, "R5 violation: {}", errors.join("; "))
94 }
95 ValidationError::CausalViolation { blame, .. } => {
96 write!(f, "causal violation: {}", blame)
97 }
98 ValidationError::ShapeViolation { blame, .. } => {
99 write!(f, "shape violation: {}", blame)
100 }
101 ValidationError::MalformedMessage { reason } => {
102 write!(f, "malformed message: {reason}")
103 }
104 ValidationError::MalformedDialect { reason } => {
105 write!(f, "malformed dialect: {reason}")
106 }
107 }
108 }
109}
110
111#[cfg(feature = "std")]
112impl std::error::Error for ValidationError {}
113
114#[derive(Debug, Clone, PartialEq, Eq)]
116#[allow(clippy::large_enum_variant)]
117pub enum PipelineResult {
118 Success(Message),
119 ParseError(ParseError),
120 ValidationError(ValidationError),
121 Pending {
128 message: Message,
129 reason: PendingReason,
130 },
131 Buffered {
134 message: Message,
135 },
136}
137
138pub struct PipelineContext<'a, S: MessageStore> {
144 pub registry: &'a DialectRegistry,
145 pub store: &'a S,
146 pub policy: UnknownPredecessorPolicy,
150}
151
152impl<'a, S: MessageStore> PipelineContext<'a, S> {
153 pub fn new(registry: &'a DialectRegistry, store: &'a S) -> Self {
155 Self {
156 registry,
157 store,
158 policy: UnknownPredecessorPolicy::default(),
159 }
160 }
161
162 pub fn with_policy(
164 registry: &'a DialectRegistry,
165 store: &'a S,
166 policy: UnknownPredecessorPolicy,
167 ) -> Self {
168 Self {
169 registry,
170 store,
171 policy,
172 }
173 }
174}
175
176pub fn run_pipeline(input: &str) -> PipelineResult {
184 let sexpr = match parser::parse(input) {
185 Ok(e) => e,
186 Err(e) => return PipelineResult::ParseError(e),
187 };
188
189 let message = match crate::message_parser::parse_message(&sexpr) {
190 Ok(m) => m,
191 Err(reason) => {
192 return PipelineResult::ValidationError(ValidationError::MalformedMessage { reason })
193 }
194 };
195
196 if let Err(err) = validate_meta_dialect(&message, None) {
198 return PipelineResult::ValidationError(err);
199 }
200
201 PipelineResult::Success(message)
202}
203
204pub fn run_pipeline_full<S: MessageStore>(
212 input: &str,
213 ctx: &PipelineContext<'_, S>,
214) -> PipelineResult {
215 let sexpr = match parser::parse(input) {
217 Ok(e) => e,
218 Err(e) => return PipelineResult::ParseError(e),
219 };
220
221 let message = match crate::message_parser::parse_message(&sexpr) {
223 Ok(m) => m,
224 Err(reason) => {
225 return PipelineResult::ValidationError(ValidationError::MalformedMessage { reason })
226 }
227 };
228
229 if let Err(err) = validate_meta_dialect(&message, Some(ctx.registry)) {
233 return PipelineResult::ValidationError(err);
234 }
235
236 let inner_simple = message.innermost_simple();
246 if let Some(Message::Simple {
247 caused_by,
248 thread,
249 performative,
250 ..
251 }) = inner_simple
252 {
253 let performative = Some(performative);
254
255 if let Some(perf) = performative {
265 let perf_name = perf.name();
266 let thread_id = ThreadId(thread.clone().unwrap_or_else(|| String::from("default")));
267
268 for d in ctx.registry.iter() {
269 let Some(ref proto) = d.causal_protocol else {
270 continue;
271 };
272 if !proto.steps.contains_key(perf_name) {
273 continue;
274 }
275
276 let result = cbcl_core::protocol::verify_causal(
277 perf_name,
278 caused_by.as_ref(),
279 ctx.store,
280 proto,
281 &thread_id,
282 );
283
284 match apply_policy(&result, &ctx.policy) {
285 PolicyOutcome::Accept => {}
286 PolicyOutcome::Reject(cv) => {
287 let blame =
288 ViolationError::from_causal_violation(&cv, None, thread.clone())
289 .with_dialect_context(
290 &d.name,
291 d.author.as_deref(),
292 d.hash.as_deref(),
293 Some(perf_name),
294 );
295 blame.record_metrics(&d.name);
296 return PipelineResult::ValidationError(ValidationError::CausalViolation {
297 violation: cv,
298 blame,
299 });
300 }
301 PolicyOutcome::Pending(reason) => {
302 return PipelineResult::Pending { message, reason };
303 }
304 PolicyOutcome::Buffered => {
305 return PipelineResult::Buffered { message };
306 }
307 }
308 }
309 }
310
311 let eval_result = match evaluate_without_shape_check(&message, ctx.registry) {
314 Ok(r) => r,
315 Err(eval_err) => {
316 return PipelineResult::ValidationError(eval_error_to_validation(
317 eval_err,
318 thread.clone(),
319 ))
320 }
321 };
322
323 if let Some(perf) = performative {
326 let perf_name = perf.name();
327 for dialect in ctx.registry.iter() {
328 for shape in &dialect.shapes {
329 if shape.performative == perf_name {
330 if let Err(sv) = shape.check(&eval_result.expanded) {
331 let blame = ViolationError::from_shape_violation(
332 &sv,
333 None,
334 thread.clone(),
335 None,
336 )
337 .with_dialect_context(
338 &dialect.name,
339 dialect.author.as_deref(),
340 dialect.hash.as_deref(),
341 Some(perf_name),
342 );
343 blame.record_metrics(&dialect.name);
344 return PipelineResult::ValidationError(
345 ValidationError::ShapeViolation {
346 violation: sv,
347 blame,
348 },
349 );
350 }
351 }
352 }
353 }
354 }
355 }
356
357 PipelineResult::Success(message)
358}
359
360#[allow(clippy::result_large_err)]
366fn validate_meta_dialect(
367 message: &Message,
368 registry: Option<&DialectRegistry>,
369) -> Result<(), ValidationError> {
370 if let Message::Meta { ref dialect_def } = message {
371 if let SExpr::List(items) = dialect_def {
372 if items.is_empty() {
373 return Ok(());
374 }
375
376 if items[0].is_symbol("define") {
378 return validate_define_dialect(dialect_def, registry);
379 }
380
381 if items[0].is_symbol("teach") {
384 for item in items.iter().skip(1) {
387 if let SExpr::List(inner_items) = item {
388 if !inner_items.is_empty() && inner_items[0].is_symbol("define") {
389 return validate_define_dialect(item, registry);
390 }
391 }
392 }
393 }
395 }
396 }
397 Ok(())
398}
399
400#[allow(clippy::result_large_err)]
401fn validate_define_dialect(
402 dialect_def: &SExpr,
403 registry: Option<&DialectRegistry>,
404) -> Result<(), ValidationError> {
405 let dialect = crate::dialect_parser::parse_dialect(dialect_def)
406 .map_err(|reason| ValidationError::MalformedDialect { reason })?;
407
408 let recursive = r1::r1_violations(&dialect);
409 if !recursive.is_empty() {
410 return Err(ValidationError::R1RecursivePerformative {
411 performatives: recursive,
412 });
413 }
414
415 if let Some((field, value)) = invalid_resource_bound(&dialect) {
416 return Err(ValidationError::R2ResourceBoundsInvalid { field, value });
417 }
418
419 let overrides = r3::r3_violations(&dialect);
420 if !overrides.is_empty() {
421 return Err(ValidationError::R3CoreOverride {
422 performatives: overrides,
423 });
424 }
425
426 let base = cbcl_core::dialect::base_dialect();
436 let mut ancestors: alloc::vec::Vec<&cbcl_core::dialect::Dialect> = alloc::vec![];
437 let mut credited_base = false;
438 if let Some(reg) = registry {
439 for name in &dialect.extends {
440 let resolved = if name == "cbcl" {
441 "cbcl-base"
442 } else {
443 name.as_str()
444 };
445 if let Some(parent) = reg.find_by_name(resolved) {
446 ancestors.push(parent);
447 if resolved == base.name {
448 credited_base = true;
449 }
450 }
451 }
452 }
453 if !credited_base {
454 let extends_base = dialect
455 .extends
456 .iter()
457 .any(|name| name == "cbcl" || name == &base.name);
458 if extends_base {
459 ancestors.push(&base);
460 }
461 }
462 let r5_errors = r5::r5_violations_with_ancestors(&dialect, &ancestors);
463 if !r5_errors.is_empty() {
464 return Err(ValidationError::R5Violation { errors: r5_errors });
465 }
466
467 Ok(())
468}
469
470fn invalid_resource_bound(dialect: &Dialect) -> Option<(&'static str, u32)> {
471 let bounds = &dialect.resources;
472 if bounds.max_depth == 0 || bounds.max_depth > 64 {
473 return Some(("max_depth", bounds.max_depth));
474 }
475 if bounds.max_expansion_size == 0 || bounds.max_expansion_size > 8192 {
476 return Some(("max_expansion_size", bounds.max_expansion_size));
477 }
478 None
479}
480
481fn eval_error_to_validation(err: EvalError, thread: Option<String>) -> ValidationError {
487 match err {
488 EvalError::UnknownPerformative(name) => ValidationError::MalformedMessage {
489 reason: alloc::format!("unknown performative: {name}"),
490 },
491 EvalError::UnscopedDialectPerformative(name) => ValidationError::MalformedMessage {
495 reason: alloc::format!(
496 "dialect performative '{name}' invoked outside (lang <dialect> ...); \
497 the message must name the dialect that defines it"
498 ),
499 },
500 EvalError::TemplateExpansionFailed { performative: _ } => ValidationError::R2FuelExhausted,
501 EvalError::UnknownDialect(name) => ValidationError::MalformedMessage {
502 reason: alloc::format!("unknown dialect: {name}"),
503 },
504 EvalError::MalformedMessage(reason) => ValidationError::MalformedMessage { reason },
505 EvalError::ShapeViolation(sv) => {
506 let blame = ViolationError::from_shape_violation(&sv, None, thread, None);
507 ValidationError::ShapeViolation {
508 violation: sv,
509 blame,
510 }
511 }
512 }
513}
514
515#[cfg(test)]
516mod tests {
517 use super::*;
518 use alloc::collections::BTreeMap;
519 use cbcl_core::dialect::{DialectRegistry, PerformativeDef, ResourceBounds};
520 use cbcl_core::message::{CausedBy, MessageType, Performative};
521 use cbcl_core::protocol::{CausalProtocol, NodeRef, StepDecl};
522 use cbcl_core::sexpr::Atom;
523 use cbcl_core::shape::{ShapeConstraint, ShapeRule, TypeConstraint};
524 use cbcl_core::store::{ContentHash, ThreadId, ThreadedMessageStore};
525
526 fn effect_template(action: &str) -> SExpr {
527 SExpr::List(alloc::vec![
528 SExpr::Atom(Atom::Symbol(String::from("effect"))),
529 SExpr::Atom(Atom::Symbol(String::from(action))),
530 ])
531 }
532
533 fn make_simple_msg(perf: &str, caused_by: Option<CausedBy>) -> Message {
534 Message::Simple {
535 performative: Performative::Custom(String::from(perf)),
536 recipient: None,
537 content: SExpr::Atom(Atom::Str(String::from("test"))),
538 params: alloc::vec![],
539 thread: None,
540 sender: None,
541 caused_by,
542 }
543 }
544
545 #[test]
548 fn pipeline_parse_error() {
549 let result = run_pipeline("(unclosed");
550 assert!(matches!(result, PipelineResult::ParseError(_)));
551 }
552
553 #[test]
554 fn pipeline_simple_message() {
555 let result = run_pipeline("(tell \"hello\")");
556 assert!(matches!(result, PipelineResult::Success(_)));
557 if let PipelineResult::Success(msg) = result {
558 assert_eq!(msg.message_type(), MessageType::Simple);
559 }
560 }
561
562 #[test]
563 fn pipeline_meta_define() {
564 let input = "(meta (define test-dialect (cbcl) @author))";
565 let result = run_pipeline(input);
566 assert!(matches!(result, PipelineResult::Success(_)));
567 if let PipelineResult::Success(msg) = result {
568 assert_eq!(msg.message_type(), MessageType::Meta);
569 }
570 }
571
572 #[test]
573 fn pipeline_malformed_dialect() {
574 let input = "(meta (define))"; let result = run_pipeline(input);
576 assert!(matches!(
577 result,
578 PipelineResult::ValidationError(ValidationError::MalformedDialect { .. })
579 ));
580 }
581
582 #[test]
583 fn pipeline_custom_performative() {
584 let result = run_pipeline(
585 "(lang cbcl-planning (share-conditional pickup box-location box-in-hand))",
586 );
587 assert!(matches!(result, PipelineResult::Success(_)));
588 }
589
590 #[test]
591 fn pipeline_meta_query() {
592 let result = run_pipeline("(meta (query (speak? cbcl-planning)))");
593 assert!(matches!(result, PipelineResult::Success(_)));
594 }
595
596 #[test]
597 fn pipeline_rejects_r3_core_override() {
598 let result = run_pipeline("(meta (define bad (cbcl) @author (extend tell () x)))");
599 assert!(matches!(
600 result,
601 PipelineResult::ValidationError(ValidationError::R3CoreOverride { .. })
602 ));
603 }
604
605 #[test]
606 fn pipeline_rejects_mutual_recursion() {
607 let result = run_pipeline(
608 "(meta (define cyclic (cbcl) @author (extend ping () (pong)) (extend pong () (ping))))",
609 );
610 assert!(matches!(
611 result,
612 PipelineResult::ValidationError(ValidationError::R1RecursivePerformative { .. })
613 ));
614 }
615
616 #[test]
619 fn pipeline_teach_validates_r3() {
620 let result =
621 run_pipeline("(meta (teach @bob (define bad (cbcl) @author (extend tell () x))))");
622 assert!(matches!(
623 result,
624 PipelineResult::ValidationError(ValidationError::R3CoreOverride { .. })
625 ));
626 }
627
628 #[test]
629 fn pipeline_teach_valid_passes() {
630 let result = run_pipeline("(meta (teach @bob (define good-dialect (cbcl) @author)))");
631 assert!(matches!(result, PipelineResult::Success(_)));
632 }
633
634 #[test]
637 fn full_pipeline_simple_message_passes() {
638 let registry = DialectRegistry::new();
639 let store = ThreadedMessageStore::new();
640 let ctx = PipelineContext::new(®istry, &store);
641 let result = run_pipeline_full("(tell \"hello\")", &ctx);
642 assert!(matches!(result, PipelineResult::Success(_)));
643 }
644
645 #[test]
646 fn full_pipeline_rejects_causal_violation() {
647 let mut registry = DialectRegistry::new();
648
649 let mut steps = BTreeMap::new();
651 steps.insert(
652 "begin".into(),
653 StepDecl {
654 performative: "begin".into(),
655 predecessors: alloc::vec![],
656 successors: alloc::vec![NodeRef::Single("greet".into())],
657 },
658 );
659 steps.insert(
660 "greet".into(),
661 StepDecl {
662 performative: "greet".into(),
663 predecessors: alloc::vec![NodeRef::Single("begin".into())],
664 successors: alloc::vec![],
665 },
666 );
667 let proto = CausalProtocol { steps };
668
669 registry
670 .install(cbcl_core::dialect::Dialect {
671 types: Default::default(),
672 roles: Vec::new(),
673 state: None,
674 state_bounds: None,
675 causal_locality: Default::default(),
676 name: String::from("proto-dialect"),
677 extends: alloc::vec![String::from("cbcl")],
678 author: None,
679 performatives: alloc::vec![PerformativeDef {
680 role: None,
681 name: String::from("greet"),
682 params: alloc::vec![],
683 template: effect_template("greet-action"),
684 }],
685 resources: ResourceBounds {
686 max_depth: 8,
687 max_expansion_size: 512,
688 },
689 examples: alloc::vec![],
690 signature: None,
691 hash: None,
692 protocol: None,
693 causal_protocol: Some(proto),
694 shapes: alloc::vec![],
695 })
696 .unwrap();
697
698 let store = ThreadedMessageStore::new();
699 let ctx = PipelineContext::new(®istry, &store);
700
701 let result = run_pipeline_full("(lang proto-dialect (greet \"hi\"))", &ctx);
703 assert!(
704 matches!(
705 result,
706 PipelineResult::ValidationError(ValidationError::CausalViolation { .. })
707 ),
708 "expected causal violation, got {:?}",
709 result
710 );
711 }
712
713 #[test]
714 fn full_pipeline_shape_violation_rejected() {
715 let mut registry = DialectRegistry::new();
716
717 registry
719 .install(cbcl_core::dialect::Dialect {
720 types: Default::default(),
721 roles: Vec::new(),
722 state: None,
723 state_bounds: None,
724 causal_locality: Default::default(),
725 name: String::from("shape-dialect"),
726 extends: alloc::vec![String::from("cbcl")],
727 author: None,
728 performatives: alloc::vec![PerformativeDef {
729 role: None,
730 name: String::from("propose"),
731 params: alloc::vec![],
732 template: effect_template("propose-action"),
733 }],
734 resources: ResourceBounds {
735 max_depth: 8,
736 max_expansion_size: 512,
737 },
738 examples: alloc::vec![],
739 signature: None,
740 hash: None,
741 protocol: None,
742 causal_protocol: None,
743 shapes: alloc::vec![ShapeConstraint {
744 performative: String::from("propose"),
745 rules: alloc::vec![ShapeRule::Require {
746 keyword: String::from("target"),
747 type_constraint: Some(TypeConstraint::String),
748 children: alloc::vec![],
749 }],
750 }],
751 })
752 .unwrap();
753
754 let store = ThreadedMessageStore::new();
755 let ctx = PipelineContext::new(®istry, &store);
756
757 let result = run_pipeline_full("(lang shape-dialect (propose \"idea\"))", &ctx);
759 assert!(
760 matches!(
761 result,
762 PipelineResult::ValidationError(ValidationError::ShapeViolation { .. })
763 ),
764 "expected shape violation, got {:?}",
765 result
766 );
767 }
768
769 #[test]
770 fn full_pipeline_causal_valid_with_predecessor() {
771 let mut registry = DialectRegistry::new();
772
773 let mut steps = BTreeMap::new();
775 steps.insert(
776 "begin".into(),
777 StepDecl {
778 performative: "begin".into(),
779 predecessors: alloc::vec![],
780 successors: alloc::vec![NodeRef::Single("ack".into())],
781 },
782 );
783 steps.insert(
784 "ack".into(),
785 StepDecl {
786 performative: "ack".into(),
787 predecessors: alloc::vec![NodeRef::Single("begin".into())],
788 successors: alloc::vec![],
789 },
790 );
791 let proto = CausalProtocol { steps };
792
793 registry
794 .install(cbcl_core::dialect::Dialect {
795 types: Default::default(),
796 roles: Vec::new(),
797 state: None,
798 state_bounds: None,
799 causal_locality: Default::default(),
800 name: String::from("ack-dialect"),
801 extends: alloc::vec![String::from("cbcl")],
802 author: None,
803 performatives: alloc::vec![PerformativeDef {
804 role: None,
805 name: String::from("ack"),
806 params: alloc::vec![],
807 template: effect_template("ack-action"),
808 }],
809 resources: ResourceBounds {
810 max_depth: 8,
811 max_expansion_size: 512,
812 },
813 examples: alloc::vec![],
814 signature: None,
815 hash: None,
816 protocol: None,
817 causal_protocol: Some(proto),
818 shapes: alloc::vec![],
819 })
820 .unwrap();
821
822 let thread = ThreadId(String::from("default"));
823 let mut store = ThreadedMessageStore::new();
824 store.append(
826 ContentHash(String::from("abc123")),
827 thread.clone(),
828 make_simple_msg("begin", Some(CausedBy::Begin)),
829 );
830
831 let ctx = PipelineContext::new(®istry, &store);
832
833 let result = run_pipeline_full(
835 "(lang ack-dialect (ack \"done\" :caused-by \"abc123\"))",
836 &ctx,
837 );
838 assert!(
839 matches!(result, PipelineResult::Success(_)),
840 "expected success, got {:?}",
841 result
842 );
843 }
844
845 #[test]
846 fn full_pipeline_meta_define_still_validated() {
847 let registry = DialectRegistry::new();
848 let store = ThreadedMessageStore::new();
849 let ctx = PipelineContext::new(®istry, &store);
850 let result = run_pipeline_full(
852 "(meta (define bad (cbcl) @author (extend tell () x)))",
853 &ctx,
854 );
855 assert!(matches!(
856 result,
857 PipelineResult::ValidationError(ValidationError::R3CoreOverride { .. })
858 ));
859 }
860
861 #[test]
862 fn full_pipeline_teach_validated() {
863 let registry = DialectRegistry::new();
864 let store = ThreadedMessageStore::new();
865 let ctx = PipelineContext::new(®istry, &store);
866 let result = run_pipeline_full(
867 "(meta (teach @bob (define bad (cbcl) @author (extend tell () x))))",
868 &ctx,
869 );
870 assert!(matches!(
871 result,
872 PipelineResult::ValidationError(ValidationError::R3CoreOverride { .. })
873 ));
874 }
875
876 fn ack_dialect_registry() -> DialectRegistry {
879 let mut registry = DialectRegistry::new();
880 let mut steps = BTreeMap::new();
881 steps.insert(
882 "begin".into(),
883 StepDecl {
884 performative: "begin".into(),
885 predecessors: alloc::vec![],
886 successors: alloc::vec![NodeRef::Single("ack".into())],
887 },
888 );
889 steps.insert(
890 "ack".into(),
891 StepDecl {
892 performative: "ack".into(),
893 predecessors: alloc::vec![NodeRef::Single("begin".into())],
894 successors: alloc::vec![],
895 },
896 );
897 let proto = CausalProtocol { steps };
898
899 registry
900 .install(cbcl_core::dialect::Dialect {
901 types: Default::default(),
902 roles: Vec::new(),
903 state: None,
904 state_bounds: None,
905 causal_locality: Default::default(),
906 name: String::from("ack-dialect"),
907 extends: alloc::vec![String::from("cbcl")],
908 author: None,
909 performatives: alloc::vec![PerformativeDef {
910 role: None,
911 name: String::from("ack"),
912 params: alloc::vec![],
913 template: effect_template("ack-action"),
914 }],
915 resources: ResourceBounds {
916 max_depth: 8,
917 max_expansion_size: 512,
918 },
919 examples: alloc::vec![],
920 signature: None,
921 hash: None,
922 protocol: None,
923 causal_protocol: Some(proto),
924 shapes: alloc::vec![],
925 })
926 .unwrap();
927 registry
928 }
929
930 #[test]
931 fn full_pipeline_unknown_predecessor_rejects_under_default_policy() {
932 let registry = ack_dialect_registry();
933 let store = ThreadedMessageStore::new(); let ctx = PipelineContext::new(®istry, &store);
935
936 let result = run_pipeline_full(
938 "(lang ack-dialect (ack \"done\" :caused-by \"missing-hash\"))",
939 &ctx,
940 );
941 assert!(
942 matches!(
943 result,
944 PipelineResult::Pending {
945 reason: cbcl_core::policy::PendingReason::CausalPending,
946 ..
947 }
948 ),
949 "expected Pending under default Reject policy, got {:?}",
950 result
951 );
952 }
953
954 #[test]
955 fn full_pipeline_unknown_predecessor_buffers_under_buffer_policy() {
956 let registry = ack_dialect_registry();
957 let store = ThreadedMessageStore::new();
958 let ctx = PipelineContext::with_policy(
959 ®istry,
960 &store,
961 cbcl_core::policy::UnknownPredecessorPolicy::buffer(60),
962 );
963
964 let result = run_pipeline_full(
965 "(lang ack-dialect (ack \"done\" :caused-by \"missing-hash\"))",
966 &ctx,
967 );
968 assert!(
969 matches!(result, PipelineResult::Buffered { .. }),
970 "expected Buffered under Buffer policy, got {:?}",
971 result
972 );
973 }
974
975 #[test]
980 fn full_pipeline_causal_violation_takes_precedence_over_shape() {
981 let mut registry = DialectRegistry::new();
982
983 let mut steps = BTreeMap::new();
985 steps.insert(
986 "begin".into(),
987 StepDecl {
988 performative: "begin".into(),
989 predecessors: alloc::vec![],
990 successors: alloc::vec![NodeRef::Single("ack".into())],
991 },
992 );
993 steps.insert(
994 "ack".into(),
995 StepDecl {
996 performative: "ack".into(),
997 predecessors: alloc::vec![NodeRef::Single("begin".into())],
998 successors: alloc::vec![],
999 },
1000 );
1001 let proto = CausalProtocol { steps };
1002
1003 registry
1004 .install(cbcl_core::dialect::Dialect {
1005 types: Default::default(),
1006 roles: Vec::new(),
1007 state: None,
1008 state_bounds: None,
1009 causal_locality: Default::default(),
1010 name: String::from("ack-with-shape"),
1011 extends: alloc::vec![String::from("cbcl")],
1012 author: None,
1013 performatives: alloc::vec![PerformativeDef {
1014 role: None,
1015 name: String::from("ack"),
1016 params: alloc::vec![],
1017 template: effect_template("ack-action"),
1018 }],
1019 resources: ResourceBounds {
1020 max_depth: 8,
1021 max_expansion_size: 512,
1022 },
1023 examples: alloc::vec![],
1024 signature: None,
1025 hash: None,
1026 protocol: None,
1027 causal_protocol: Some(proto),
1028 shapes: alloc::vec![ShapeConstraint {
1029 performative: String::from("ack"),
1030 rules: alloc::vec![ShapeRule::Require {
1031 keyword: String::from("target"),
1032 type_constraint: Some(TypeConstraint::String),
1033 children: alloc::vec![],
1034 }],
1035 }],
1036 })
1037 .unwrap();
1038
1039 let store = ThreadedMessageStore::new();
1040 let ctx = PipelineContext::new(®istry, &store);
1041
1042 let result = run_pipeline_full("(lang ack-with-shape (ack \"done\"))", &ctx);
1045 assert!(
1046 matches!(
1047 result,
1048 PipelineResult::ValidationError(ValidationError::CausalViolation { .. })
1049 ),
1050 "expected CausalViolation to take precedence, got {:?}",
1051 result
1052 );
1053 }
1054
1055 #[test]
1060 fn full_pipeline_child_protocol_on_core_perf_is_enforced() {
1061 let mut registry = DialectRegistry::new();
1062 let mut steps = BTreeMap::new();
1063 steps.insert(
1064 "begin".into(),
1065 StepDecl {
1066 performative: "begin".into(),
1067 predecessors: alloc::vec![],
1068 successors: alloc::vec![NodeRef::Single("ok".into())],
1069 },
1070 );
1071 steps.insert(
1072 "ok".into(),
1073 StepDecl {
1074 performative: "ok".into(),
1075 predecessors: alloc::vec![NodeRef::Single("begin".into())],
1076 successors: alloc::vec![],
1077 },
1078 );
1079 registry
1080 .install(cbcl_core::dialect::Dialect {
1081 types: Default::default(),
1082 roles: Vec::new(),
1083 state: None,
1084 state_bounds: None,
1085 causal_locality: Default::default(),
1086 name: String::from("ok-protocol"),
1087 extends: alloc::vec![String::from("cbcl")],
1088 author: None,
1089 performatives: alloc::vec![], resources: ResourceBounds {
1091 max_depth: 8,
1092 max_expansion_size: 512,
1093 },
1094 examples: alloc::vec![],
1095 signature: None,
1096 hash: None,
1097 protocol: None,
1098 causal_protocol: Some(CausalProtocol { steps }),
1099 shapes: alloc::vec![],
1100 })
1101 .unwrap();
1102
1103 let store = ThreadedMessageStore::new();
1104 let ctx = PipelineContext::new(®istry, &store);
1105
1106 let result = run_pipeline_full("(ok)", &ctx);
1108 assert!(
1109 matches!(
1110 result,
1111 PipelineResult::ValidationError(ValidationError::CausalViolation { .. })
1112 ),
1113 "expected child protocol on core `ok` to fire, got {:?}",
1114 result
1115 );
1116 }
1117
1118 #[test]
1122 fn full_pipeline_meta_define_credits_non_base_parent_via_registry() {
1123 let mut registry = DialectRegistry::new();
1124 registry
1126 .install(cbcl_core::dialect::Dialect {
1127 types: Default::default(),
1128 roles: Vec::new(),
1129 state: None,
1130 state_bounds: None,
1131 causal_locality: Default::default(),
1132 name: String::from("parent-dialect"),
1133 extends: alloc::vec![String::from("cbcl")],
1134 author: None,
1135 performatives: alloc::vec![PerformativeDef {
1136 role: None,
1137 name: String::from("notify"),
1138 params: alloc::vec![],
1139 template: effect_template("notify-action"),
1140 }],
1141 resources: ResourceBounds {
1142 max_depth: 8,
1143 max_expansion_size: 512,
1144 },
1145 examples: alloc::vec![],
1146 signature: None,
1147 hash: None,
1148 protocol: None,
1149 causal_protocol: None,
1150 shapes: alloc::vec![],
1151 })
1152 .unwrap();
1153
1154 let store = ThreadedMessageStore::new();
1155 let ctx = PipelineContext::new(®istry, &store);
1156
1157 let input = "\
1161 (meta (define child-dialect (parent-dialect) @author \
1162 (protocol (then begin notify))))";
1163 let result = run_pipeline_full(input, &ctx);
1164 assert!(
1165 matches!(result, PipelineResult::Success(_)),
1166 "expected meta-define with registry ancestor to pass, got {:?}",
1167 result
1168 );
1169 }
1170
1171 #[test]
1175 fn full_pipeline_envelope_wrapping_does_not_bypass_causal() {
1176 let registry = ack_dialect_registry();
1177 let store = ThreadedMessageStore::new();
1178 let ctx = PipelineContext::new(®istry, &store);
1179
1180 let result = run_pipeline_full(
1183 "(envelope (:from @alice) (ack \"done\" :caused-by \"missing\"))",
1184 &ctx,
1185 );
1186 assert!(
1187 !matches!(result, PipelineResult::Success(_)),
1188 "expected wrapper not to bypass verification, got Success: {result:?}"
1189 );
1190 }
1191
1192 #[test]
1193 fn full_pipeline_lang_scoped_message_does_not_bypass_causal() {
1194 let registry = ack_dialect_registry();
1195 let store = ThreadedMessageStore::new();
1196 let ctx = PipelineContext::new(®istry, &store);
1197
1198 let result = run_pipeline_full(
1200 "(lang ack-dialect (lang ack-dialect (ack \"done\" :caused-by \"missing\")))",
1201 &ctx,
1202 );
1203 assert!(
1204 !matches!(result, PipelineResult::Success(_)),
1205 "expected dialect-scoped wrapper not to bypass verification, got Success: {result:?}"
1206 );
1207 }
1208
1209 fn parse_install_hash(source: &str) -> String {
1214 let sexpr = parser::parse(source).expect("dialect source parses");
1215 let d = crate::dialect_parser::parse_dialect(&sexpr).expect("dialect extracts");
1216 assert!(d.hash.is_none(), "source declares no :hash");
1217 let mut registry = DialectRegistry::new();
1218 registry.install(d).expect("dialect installs");
1219 registry
1220 .get(1)
1221 .expect("installed at index 1")
1222 .hash
1223 .clone()
1224 .expect("install populates hash")
1225 }
1226
1227 #[test]
1228 fn parsed_dialect_hash_populated_after_install() {
1229 let h = parse_install_hash(
1230 "(define greeting-dialect (cbcl) @author (extend greet () (effect greet-action)))",
1231 );
1232 let hex = h.strip_prefix("f1220").expect("f1220 prefix");
1233 assert_eq!(hex.len(), 64);
1234 assert!(hex
1235 .chars()
1236 .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)));
1237 }
1238
1239 #[test]
1240 fn parsed_dialect_hash_stable_under_reformatting() {
1241 let compact =
1244 "(define greeting-dialect (cbcl) @author (extend greet () (effect greet-action)))";
1245 let sprawling = "(define greeting-dialect\n (cbcl)\n @author\n (extend greet\n ()\n (effect greet-action)))\n";
1246 assert_eq!(
1247 parse_install_hash(compact),
1248 parse_install_hash(sprawling),
1249 "reformatted-but-equal source must yield the identical hash"
1250 );
1251 }
1252
1253 #[test]
1254 fn parsed_dialect_hash_changes_when_performative_renamed() {
1255 let original =
1256 "(define greeting-dialect (cbcl) @author (extend greet () (effect greet-action)))";
1257 let renamed =
1258 "(define greeting-dialect (cbcl) @author (extend salute () (effect greet-action)))";
1259 assert_ne!(
1260 parse_install_hash(original),
1261 parse_install_hash(renamed),
1262 "renaming a performative must change the hash"
1263 );
1264 }
1265
1266 #[test]
1267 fn blame_carries_installed_dialect_hash() {
1268 let mut registry = DialectRegistry::new();
1272 registry
1273 .install(cbcl_core::dialect::Dialect {
1274 types: Default::default(),
1275 roles: Vec::new(),
1276 state: None,
1277 state_bounds: None,
1278 causal_locality: Default::default(),
1279 name: String::from("shape-dialect"),
1280 extends: alloc::vec![String::from("cbcl")],
1281 author: Some(String::from("@shape-author")),
1282 performatives: alloc::vec![PerformativeDef {
1283 role: None,
1284 name: String::from("propose"),
1285 params: alloc::vec![],
1286 template: effect_template("propose-action"),
1287 }],
1288 resources: ResourceBounds {
1289 max_depth: 8,
1290 max_expansion_size: 512,
1291 },
1292 examples: alloc::vec![],
1293 signature: None,
1294 hash: None,
1295 protocol: None,
1296 causal_protocol: None,
1297 shapes: alloc::vec![ShapeConstraint {
1298 performative: String::from("propose"),
1299 rules: alloc::vec![ShapeRule::Require {
1300 keyword: String::from("target"),
1301 type_constraint: Some(TypeConstraint::String),
1302 children: alloc::vec![],
1303 }],
1304 }],
1305 })
1306 .unwrap();
1307 let installed_hash = registry
1308 .find_by_name("shape-dialect")
1309 .unwrap()
1310 .hash
1311 .clone()
1312 .expect("install populates hash");
1313
1314 let store = ThreadedMessageStore::new();
1315 let ctx = PipelineContext::new(®istry, &store);
1316 let result = run_pipeline_full("(lang shape-dialect (propose \"idea\"))", &ctx);
1317 let PipelineResult::ValidationError(ValidationError::ShapeViolation { blame, .. }) = result
1318 else {
1319 panic!("expected shape violation, got {result:?}");
1320 };
1321 assert_eq!(blame.dialect_hash.as_deref(), Some(installed_hash.as_str()));
1322 assert_eq!(blame.dialect.as_deref(), Some("shape-dialect"));
1323 assert_eq!(blame.performative.as_deref(), Some("propose"));
1324 let rendered = alloc::format!("{}", blame.to_sexpr());
1325 assert!(
1326 rendered.contains("dialect-hash") && rendered.contains(&installed_hash),
1327 "blame wire form must carry the installed dialect hash: {rendered}"
1328 );
1329 }
1330}