Rust Rule Engine v1.2.0 ๐ฆโก๐
A high-performance rule engine for Rust with RETE-UL algorithm, Parallel Execution, CLIPS-inspired Module System, Production-Ready Backward Chaining (100-1000x faster!), Plugin System, and GRL (Grule Rule Language) support. Designed for production use with excellent performance and Drools compatibility.
๐ GitHub | Documentation | Crates.io
โจ What's New in v1.2.0 ๐
๐ฏ Module System for Large-Scale Rule Organization!
This release introduces CLIPS-inspired module system for organizing and managing large-scale rule bases. Organize complex applications with modular rule organization, import/export control, and namespace management.
๐ Major Features:
โ CLIPS-Inspired Module System (NEW!)
- โ Modular rule organization with namespaces
- โ Import/Export directives for visibility control
- โ Clear module boundaries with GRL syntax
- โ Module-specific rule focusing
- โ 100% backward compatible with v1.1.x
- โ All 85 existing examples work unchanged
โ GRL Parser Enhancements (NEW!)
- โ
defmoduledirective support for module declarations - โ
Module context markers (
;; MODULE: NAME) for rule organization - โ Export/import specifications with visibility control
- โ
New
parse_with_modules()API for module-aware parsing - โ Automatic rule-to-module mapping via backward search algorithm
- โ Performance: <1ms for typical files
โ Module Management APIs (NEW!)
- โ ModuleManager for complete module lifecycle
- โ Module visibility and access control enforcement
- โ Rule-to-module mapping with HashMap lookup
- โ Export/import directive enforcement
- โ Namespace isolation for large-scale rule bases
โ Production-Ready Backward Chaining
- โ 100-1000x performance with O(1) indexing
- โ All v1.1.x features fully integrated
๐ Major Milestones:
โ Complete Backward Chaining System (88% โ Production Ready!)
- โ All Phase 1 tasks 100% complete
- โ Phase 2 testing & docs 92% complete
- โ Phase 3 optimization 65% complete
- โ 100-1000x proven speedup with O(1) Conclusion Index
- โ Scales to 10,000+ rules efficiently
โ Module System (NEW in v1.2.0!)
- โ CLIPS-inspired module system with full support
- โ GRL parser with defmodule directives
- โ Import/export control with visibility rules
- โ Module-aware rule focusing
- โ 100% backward compatible (all 85 examples work unchanged)
- โ Automatic module assignment via backward search
- โ Performance: <1ms parsing for typical files
โ Comprehensive Testing (39 unit tests + 15 examples)
- โ 21 expression parser tests
- โ 10 conclusion index tests
- โ 8 unification tests
- โ 15 working examples (11 demos + 4 test suites)
- โ All tests passing
โ Performance Benchmarks (9 Criterion groups)
- โ Expression parsing: <20ยตs
- โ Index lookup: ~200ns (O(1) constant time)
- โ Query execution: <10ms for 100 rules
- โ Proven 100-1000x speedup ๐ฅ
โ Complete Documentation (5 comprehensive guides)
- โ Quick Start Guide (5-minute getting started)
- โ Troubleshooting Guide (comprehensive FAQ)
- โ Performance Analysis (detailed benchmarks)
- โ Beta Release Summary (migration guide)
- โ Implementation Plan (technical details)
๐ง What's Ready for Production:
โ Module System - Organize large rule bases (NEW!) โ RETE-style conclusion index - O(1) rule lookup โ Unification system - Variable bindings & pattern matching โ Core backward chaining engine - Goal-driven reasoning โ All 3 search strategies - DFS, BFS, Iterative Deepening โ Complex condition evaluation - AND, OR, NOT, EXISTS, FORALL โ Safety mechanisms - Cycle detection, depth limits โ GRL query syntax - Declarative queries with actions โ TMS integration - Logical facts with cascade retraction โ Rollback system - Speculative changes with undo โ Missing facts analysis - What's needed to prove goals โ Proof traces - Explanation of reasoning chains โ Performance benchmarks - Comprehensive benchmark suite
๐ Production Recommendations:
Safe configurations:
let config = BackwardConfig ;
Supported use cases:
- โ Diagnostic systems (medical, technical troubleshooting)
- โ Access control & approval flows
- โ Compliance checking & validation
- โ Question answering (yes/no queries)
- โ Missing facts detection
- โ Expert systems with goal-driven reasoning
- โ Financial decision making (loan approvals, credit checks)
- โ Product recommendations & AI systems
Documentation:
- Module System Guide - Module organization & best practices ๐
- Module Parsing Guide - Parser internals & algorithms ๐
- Parser Examples - Real-world module examples ๐
- Quick Start Guide - 5-minute getting started
- Troubleshooting Guide - Common issues & FAQ
- Performance Analysis - Benchmark results
- Architecture Overview - Technical details
- Full Changelog - Complete v1.1.0 changes
Module System Example:
; Define modules with export/import control
defmodule SENSORS {
export: all
}
defmodule CONTROL {
import: SENSORS (rules * (templates *))
export: all
}
; Module context for SENSORS rules
;; MODULE: SENSORS
rule "CheckHighTemperature" {
when: Temperature > 30
then: ActivateCooling();
}
; Module context for CONTROL rules
;; MODULE: CONTROL
rule "ActivateCooling" {
when: CoolingNeeded == true
then: System.Cooling = "ON";
}
Module System Usage:
use GRLParser;
use ModuleManager;
// Parse GRL with module support
let grl_content = read_to_string?;
let parsed = parse_with_modules?;
// Access parsed rules and module information
println!;
println!;
// Load rules into engine with module context
let mut engine = new;
engine.load_rules;
engine.execute;
Backward Chaining Example:
use ;
// Load rules from GRL file
let rules = load_rules_from_file;
let mut kb = new;
for rule in parse_rules?
// Load query definition
let query_str = load_query_from_file;
// Set up facts
let mut facts = new;
facts.set;
facts.set;
// Execute backward chaining query
let query = parse?;
let mut bc_engine = new;
let result = execute?;
if result.provable else
GRL Query Syntax:
query "CheckAutoApproval" {
goal: Order.AutoApproved == true && Order.RequiresManualReview != true
strategy: depth-first
max-depth: 10
on-success: {
Order.Status = "APPROVED";
Order.ProcessingTime = "Instant";
LogMessage("โ
Order auto-approved");
}
on-failure: {
Order.Status = "PENDING_REVIEW";
Order.ProcessingTime = "1-2 business days";
LogMessage("โณ Manual review needed");
}
}
Use Cases:
- Medical Diagnosis - Work backwards from symptoms to identify diseases
- E-commerce Approval - Determine if orders should be auto-approved
- Detective Systems - Solve crimes by proving hypotheses from evidence
- Decision Trees - Classification and recommendation engines
- Expert Systems - Knowledge-based reasoning and inference
Examples (16 working examples):
Demo Applications (12):
- Simple Query Demo - Basic backward chaining
- RETE Index Demo - O(1) performance showcase ๐ฅ
- Multiple Solutions Demo - Find all proof paths (GRL-based) ๐
- Medical Diagnosis - Disease diagnosis system
- E-commerce Approval - Order approval workflow
- Detective System - Crime-solving inference
- Loan Approval - Financial decisions (29 rules)
- Family Relations - Relationship inference (21 rules)
- Access Control - RBAC permissions (26 rules)
- Product Recommendations - AI recommendations (30 rules)
- GRL Query Demo - Query language features
- Unification Demo - Variable bindings & pattern matching
Test Suites (4):
- Comprehensive Test - 12 feature tests
- Edge Cases Test - 8 correctness tests
- Critical Tests - 10 safety tests
- Unit Tests - 44 unit tests (21 parser + 10 index + 8 unification + 5 multiple solutions) ๐
Technical Features:
- O(1) Conclusion Index - HashMap-based rule lookup (100-1000x speedup) โ ๐
- Expression AST - Full boolean logic parsing (&&, ||, !, ==, !=, <, >, <=, >=) โ
- Unification System - Variable bindings & pattern matching โ ๐
- Search Strategies - DFS, BFS, Iterative Deepening โ
- Memoization - Automatic caching of proven goals โ
- Cycle Detection - Prevent infinite loops in recursive proofs โ
- Proof Traces - Full explanation of reasoning chains โ
- Query Statistics - Goals explored, rules evaluated, execution time โ
- Rule Executor - Shared condition/action evaluation โ
- Rollback System - Undo frames for speculative changes โ
Production Ready Status (88% Complete):
- โ
Phase 1 (100%): Core features complete
- Expression parser (21 tests)
- Conclusion index (10 tests)
- Unification (8 tests)
- Rule execution
- โ
Phase 2 (92%): Quality & testing
- 44 unit tests + 15 examples
- 9 Criterion benchmark groups
- 5 comprehensive documentation guides
- โ
Phase 3 (65%): Optimization
- O(1) indexing proven (100-1000x speedup)
- Performance profiling complete
Production Recommendations:
- โ PRODUCTION READY: Single-threaded use with all core features
- โ PRODUCTION READY: Diagnostic systems, decision making, expert systems
- โ PRODUCTION READY: Up to 10,000+ rules with excellent performance
- โ STABLE API: All core APIs finalized and documented
๐ Quick Start Guide โ | ๐ Performance Analysis โ | ๐ Examples โ
โจ Previous Updates - v0.19.1
๐ Bug Fixes & Improvements
- Fixed: GRL parser attribute matching for
no-loopandlock-on-activekeywords - Updated: Example files now use reorganized GRL file paths structure
- Added: Missing test files for examples
โจ What's New in v0.19.0
๐ Parallel Rule Engine - Production Ready! - Multi-threaded execution with full feature parity!
- ๐ฏ Full Feature Support - ALL advanced features now work in parallel mode:
- โ Custom function calls (thread-safe with Arc/RwLock)
- โ Pattern matching (exists/forall via PatternMatcher)
- โ Accumulate operations (sum/avg/min/max/count/collect)
- โ MultiField operations (all 7 operations)
- โ Expression evaluation with variable resolution
- โ Nested field access
- โ AND/OR/NOT compound conditions
- ๐ Smart Parallelization - Auto-detects when to parallelize based on rule count
- ๐ Benchmarked - Extensively tested with simple & complex conditions
- ๐ฏ Zero Limitations - No restrictions on rule complexity or features
- ๐ Thread-Safe - Proper synchronization with Arc/Mutex/RwLock
- ๐ Linear Scaling - Performance improves with more CPU cores
When to Use Each Engine:
- Native Engine: Simple rules, low latency requirements, single-threaded environments
- Parallel Engine: High-throughput, many rules (100+), multi-core systems, batch processing
- RETE Engine: Incremental updates, fact changes, complex pattern matching, state tracking
โจ What's New in v0.18.1
๐ Workflow Orchestration Support - Build complex multi-stage workflows with rules!
- ๐ฏ CompleteWorkflow - Mark workflows as completed with automatic timestamping
- ๐ SetWorkflowData - Store and track workflow context data as facts
- ๐ Queryable State - All workflow state stored in facts, accessible in conditions
- โฑ๏ธ Timestamp Tracking - Automatic completion time recording (ISO8601 format)
โจ What's New in v0.18.0
๐ง Truth Maintenance System (TMS) - Intelligent fact dependency tracking!
- ๐ Justification Tracking - Track why each fact exists (explicit or derived)
- โก Auto-Retraction - Derived facts automatically retracted when premises become invalid
- ๐ฒ Cascade Delete - Transitively retract all dependent facts
- ๐พ Logical Assertions - Facts derived by rules (vs explicit user assertions)
- ๐ฏ Production Ready - Full integration with RETE-UL engine
- ๐ Statistics API - Monitor TMS state and dependencies
TMS Example:
// Insert explicit fact (user-provided)
let customer_handle = engine.insert_explicit;
// Insert logical fact (rule-derived)
let gold_handle = engine.insert_logical;
// When Customer is retracted, GoldStatus is automatically retracted too!
engine.retract?; // Cascade: GoldStatus removed automatically
Technical Improvements:
- Per-Fact Evaluation: Rules check each fact separately instead of flattening all facts together
- Matched Handle Storage:
Activationstruct now tracks which specific fact matched - Handle Injection: Actions receive the exact handle of the matched fact
- Validation Check: Before executing action, verify matched fact still exists
- ActionResult Architecture: Proper queuing and processing of action side effects
- TMS Integration: Full justification tracking and cascade retraction support
โจ What's New in v0.17.2
โก 30x Parser Optimization - GRL parsing is now lightning-fast!
- ๐ 30x Speedup - Parse 15 rules in 5.7ms instead of 171ms
- ๐พ Regex Caching - 15 critical regexes cached with
once_cell::sync::Lazy - ๐ฅ Hot Path Optimized - All core parsing patterns pre-compiled
- ๐ Consistent Performance - 176-207 parses/sec (5-6ms per parse)
- โ Zero Overhead - Lazy initialization, no runtime cost after first use
- ๐ Fully Backward Compatible - 100% API compatibility, no breaking changes
- ๐ All Tests Pass - 134 unit tests + 47+ examples verified
- ๐ฏ Production Ready - Engine startup time dramatically reduced
Performance Comparison:
Before v0.17.2: 171,535 ยตs per parse (5.83 parses/sec) โ
After v0.17.2: 5,679 ยตs per parse (176 parses/sec) โ
Improvement: 30x faster ๐
Impact on Real Scenarios:
- File with 15 rules: 171ms โ 5.7ms โ
- File with 100 rules: ~1.1 sec โ ~38ms โ
- File with 1000 rules: ~11 sec โ ~380ms โ
- Rule hotloading: Now practical and responsive โ
Technical Details:
The parser was creating fresh regex objects on every parse operation. v0.18.0 implements compile-once, reuse-many pattern:
// Before: Regex compiled 18+ times per parse โ
let regex = new?;
// After: Regex compiled once, cached forever โ
static CACHED_REGEX: = new;
Coverage:
- โ Core parsing: RULE, RULE_SPLIT, WHEN_THEN, SALIENCE regexes
- โ Conditions: TEST, TYPED_TEST, FUNCTION_CALL, CONDITION, SIMPLE_CONDITION
- โ Multifields: COLLECT, COUNT, FIRST, LAST, EMPTY, NOT_EMPTY
- โ Actions: METHOD_CALL, FUNCTION_BINDING
- โ Validation: EMAIL_REGEX caching in plugins
Benchmark Results:
Test: Quick Parse (100 iterations)
Average: 5.7 ms per parse
Throughput: 176 parses/sec โ
Test: Batch Parsing (5000 iterations)
Average: 5.0 ms per parse
Throughput: 200 parses/sec โ
Test: Memory Stress (10,000 parses)
Average: 5.3 ms per parse
Throughput: 188 parses/sec โ
๐ Optimization Details โ | ๐ฌ Technical Analysis โ
โจ What's New in v0.17.0
๐ Multi-field Variables (CLIPS-style Multislot) - Complete array/collection pattern matching!
- ๐ข 9 Operations - Collect, Contains, Count, First, Last, Index, Slice, IsEmpty, NotEmpty
- ๐ฆ CLIPS Parity - 90-95% feature compatibility (up from 85-90%)
- โก Both Engines - Full support in Native Engine and RETE-UL!
- ๐ E-commerce Ready - Perfect for shopping carts, bulk orders, inventory
- ๐ฏ Pattern Matching - 100% complete (10/10 core features)
- ๐ GRL Syntax - Natural array operations in rules
- ๐ Production Ready - Comprehensive tests and examples
Example - Multi-field Operations in GRL:
rule "BulkDiscount" salience 100 no-loop {
when
Order.items count >= 5
then
Log("Bulk order detected!");
Order.discount = 0.15;
}
rule "CategorizeElectronics" salience 90 no-loop {
when
Product.tags contains "electronics"
then
Log("Electronics product found");
Product.category = "tech";
}
rule "EmptyCart" salience 80 no-loop {
when
ShoppingCart.items empty
then
Log("Cart is empty");
ShoppingCart.status = "empty";
}
rule "ProcessFirstTask" salience 70 no-loop {
when
Queue.tasks not_empty &&
Queue.tasks first $task
then
Log("Processing first task...");
Queue.current = $task;
}
Template Definition (CLIPS-style):
use ;
let order_template = new
.multislot_field // CLIPS naming
.float_field
.build;
All 9 Multifield Operations:
| Operation | GRL Syntax | CLIPS Equivalent | Use Case |
|---|---|---|---|
| Collect | Order.items $?all |
$?var |
Collect all values |
| Contains | Product.tags contains "sale" |
(member$ x $?list) |
Check membership |
| Count | Order.items count > 5 |
(length$ $?list) |
Count elements |
| First | Queue.tasks first $task |
(nth$ 1 $?list) |
Get first element |
| Last | Order.items last $item |
(nth$ -1 $?list) |
Get last element |
| Index | items[2] |
(nth$ 3 $?list) |
Access by index |
| Slice | items[1:3] |
(subseq$ $?list 2 4) |
Extract range |
| IsEmpty | Cart.items empty |
(= (length$ $?list) 0) |
Check if empty |
| NotEmpty | Queue.tasks not_empty |
(> (length$ $?list) 0) |
Check if not empty |
๐ Multifield Demo โ | โก RETE Demo โ | ๐ GRL Examples โ
Previous Updates
โจ What's New in v0.16.0
๐งฎ CLIPS-Style Expression Evaluation - Runtime arithmetic expressions in GRL rules!
- โ Arithmetic Operations - Full support for +, -, *, /, % operators
- ๐ Field References - Use fact fields in expressions (Order.quantity * Order.price)
- ๐ Chained Expressions - Values set by one action available to subsequent rules
- ๐ฏ Type Preservation - Integer ร Integer = Integer; mixed types = Float
- โก Both Engines - Works perfectly with Native Engine and RETE-UL!
- ๐ Runtime Evaluation - Expressions evaluated when rule fires
- ๐ CLIPS Syntax - Similar to CLIPS (bind ?total (* ?quantity ?price))
- โ Production Ready - Battle-tested with order processing and calculations
Example - Expression Evaluation in GRL:
rule "CalculateOrderTotal" salience 100 no-loop {
when
Order.quantity > 0 && Order.price > 0
then
Log("Calculating order total...");
Order.total = Order.quantity * Order.price;
Order.discount = Order.total * 0.1;
Order.final = Order.total - Order.discount;
}
rule "CalculateTax" salience 90 no-loop {
when
Order.final > 0
then
Log("Calculating tax...");
Order.tax = Order.final * 0.08;
Order.grandTotal = Order.final + Order.tax;
}
How it Works:
// Native Engine
let mut facts = new;
facts.set;
facts.set;
engine.execute?;
// Results:
// Order.total = 1000 (10 * 100)
// Order.discount = 100.0 (1000 * 0.1)
// Order.final = 900.0 (1000 - 100)
// Order.tax = 72.0 (900 * 0.08)
// Order.grandTotal = 972.0 (900 + 72)
Similar to Drools DRL:
- Drools:
$o.total = $o.quantity * $o.price - Rust Rule Engine:
Order.total = Order.quantity * Order.price
๐งฎ Expression Demo โ | ๐ GRL Examples โ
Previous Updates
โจ What's New in v0.15.0
๐ Thread-Safe RETE Engine - Multi-threaded support for Axum & async web services!
- ๐ฅ Send + Sync - IncrementalEngine is now Send + Sync for multi-threaded use
- โก Axum Compatible - Use with
Arc<Mutex<IncrementalEngine>>in web services - ๐ฏ Breaking Change - Action closures changed from
Box<FnMut>toArc<Fn + Send + Sync> - ๐ Migration - Replace
Box::new(move |facts| ...)withArc::new(move |facts| ...)
๐๏ธ Retract Actions - CLIPS-style fact retraction!
- ๐ฅ Retract Facts - Remove facts from working memory in GRL rules
- ๐ CLIPS Syntax -
retract($Object)just like CLIPS - ๐ฏ GRL Parser Support - Parse retract syntax from .grl files
- ๐ง Working Memory - Mark facts as retracted to prevent future matches
- ๐ Engine Integration - Full support in Native, RETE, and Parallel engines
- โ Production Ready - Session cleanup, workflow completion, resource management
Example - Retract in GRL:
rule "CleanupExpiredSession" {
when
Session.expired == true
then
Log("Session expired, cleaning up...");
retract($Session);
}
rule "RemoveInvalidUser" {
when
User.verified == false
then
retract($User);
}
Similar to CLIPS:
- CLIPS:
(retract ?f) - Rust Rule Engine:
retract($Object)
๐๏ธ Native Engine Demo โ | โก RETE Engine Demo โ | ๐ GRL Examples โ
๐ Migration Guide: v0.14.x โ v0.15.0
Breaking Change: Action closures in RETE engine are now Arc<Fn + Send + Sync> instead of Box<FnMut>.
Before (v0.14.x):
let rule = TypedReteUlRule ;
After (v0.15.0):
let rule = TypedReteUlRule ;
Why this change?
- Makes
IncrementalEngineSend + Sync for use with Axum and async web frameworks - Enables sharing the engine across threads safely with
Arc<Mutex<IncrementalEngine>> - No mutable state needed in actions (facts are passed as
&mut)
Note: If you use add_rule_with_action(), no changes needed - the function accepts closures directly.
Previous Updates
โจ What's New in v0.14.1
๐๏ธ Retract Actions - CLIPS-style fact retraction added!
- Retract facts from working memory with
retract($Object)syntax - Full GRL parser support for retract in .grl files
- Integration with Native, RETE, and Parallel engines
- Production-ready for session cleanup and workflow completion
โจ What's New in v0.14.0
๐ MAJOR UPDATE: Fully Automatic Accumulate Functions!
This release completes the accumulate feature with 100% automatic evaluation across all engine paths!
๐งฎ AUTO Accumulate Functions - Fully automated aggregation in rule conditions!
- ๐ FULLY AUTOMATIC - No manual calculation needed!
- ๐ 5 Built-in Functions - sum, count, average, min, max
- ๐ฏ GRL Parser Support - Parse
accumulate()syntax from .grl files - โก Auto Collection - Engine automatically collects matching facts
- ๐ Auto Calculation - Engine automatically runs aggregate functions
- ๐ Auto Injection - Engine automatically injects results into facts
- ๐ฏ RETE Integration - Efficient aggregation with pattern matching
- ๐ Real-time Analytics - Calculate metrics across multiple facts
- ๐ผ Business Rules - Revenue totals, order counts, averages
- โ Production Ready - Battle-tested with e-commerce analytics
Example - Just Write This in GRL:
rule "HighRevenue" {
when
accumulate(Order($amt: amount, status == "completed"), sum($amt))
then
Alert.send("High revenue!");
}
Engine does ALL of this automatically:
- โ Collects all Order facts
- โ
Filters by
status == "completed" - โ
Extracts
amountfield - โ
Runs
sum()function - โ Injects result into facts
- โ Evaluates rule condition
๐ AUTO Accumulate (RECOMMENDED) โ | โก Native & RETE-UL Demo โ | ๐ Manual API Demo โ | ๐ Parser Demo โ
โก Variable-to-Variable Comparison - Dynamic threshold comparisons!
- ๐ Compare Variables - Direct comparison between fact fields (e.g.,
Facts.L1 > Facts.L1Min) - ๐ Dynamic Thresholds - No hardcoded values, change thresholds on-the-fly
- ๐ฏ RETE-UL Support - Full integration with incremental engine
- ๐ GRL Syntax - Natural syntax:
when (Facts.value > Facts.threshold) - โก Efficient Evaluation - Leverages RETE's pattern matching
- ๐ง Flexible Rules - Same rule adapts to different threshold configurations
- โ Production Ready - Battle-tested with complex eligibility rules
See Variable Comparison Demo โ | Test Variable Comparison โ
Previous Updates
v0.13.4
๐งฎ Accumulate Functions (Initial Release) - Aggregation in rule conditions!
- ๐ 5 Built-in Functions - sum, count, average, min, max
- ๐ฏ GRL Parser Support - Parse
accumulate()syntax from .grl files - ๐ Real-time Analytics - Calculate metrics across multiple facts
- โ ๏ธ Note: Required manual injection in v0.13.4 - now fully automatic in v0.14.0!
โก Variable-to-Variable Comparison - Dynamic threshold comparisons!
- ๐ Compare Variables - Direct comparison between fact fields
- ๐ Dynamic Thresholds - Change thresholds on-the-fly
- โ Production Ready - Battle-tested
v0.13.0 (Earlier)
โก Conflict Resolution Strategies - CLIPS/Drools-inspired rule ordering!
- ๐ฏ 8 Strategies - Salience, LEX, MEA, Depth, Breadth, Simplicity, Complexity, Random
- ๐ Priority-Based - Control rule execution order with salience
- ๐ Recency-Based - Most recent facts fire first (LEX)
- ๐ Specificity - More specific rules fire first (Complexity, MEA)
- โ๏ธ Performance - Simple rules before complex (Simplicity)
- ๐ Dynamic Switching - Change strategies at runtime
- โ CLIPS Compatible - Industry-standard conflict resolution
- ๐ ~98% Drools Parity - Enhanced compatibility
See Conflict Resolution Demo โ | CLIPS Features Guide โ
Previous Updates
v0.12.0
๐งช Test CE (Conditional Element) - CLIPS-inspired arbitrary boolean expressions!
- ๐ฌ Test CE Syntax - Call arbitrary functions in rule conditions without operators
- ๐ GRL Support - Parse
test(function(args))directly from .grl files - ๐ฏ Native Engine - Fully implemented with function registry
- โก Truthy Evaluation - Automatic boolean conversion for all value types
- ๐ Negation Support - Use
!test()for negated conditions - ๐ค Combined Conditions - Mix test() with regular conditions using AND/OR
- ๐ Multiple Arguments - Support functions with any number of arguments
v0.11.0
๐ฏ Deffacts System - Initial fact definitions (CLIPS feature)!
- ๐ฆ Deffacts - Pre-defined fact sets for initial state
- ๐ Reset Support - Restore original facts with
reset_with_deffacts() - ๐ Multiple Sets - Organize initial facts by category
- โ Template Integration - Type-safe initial facts
- ๐๏ธ Builder API - Fluent interface for defining deffacts
v0.10.2
๐ง Metadata Update - Corrected author email contact information
v0.10.1
๐ RETE Performance Optimization + Comprehensive Benchmarks!
- โก RETE Fixed - Eliminated infinite loop issue, now blazing fast
- ๐ Benchmarked - Comprehensive comparison: Traditional vs RETE
- ๐ฅ 2-24x Faster - RETE shows 2x speedup at 10 rules, 24x at 50+ rules
- โ Production Ready - Max iterations guard, optimized agenda management
- ๐ Scalability Proven - ~5ยตs per rule, scales linearly
v0.10.0
- ๐ง Function Calls in WHEN - Call AI/custom functions directly in rule conditions
- ๐ Template System - Type-safe schema definitions for structured facts
- ๐ Defglobal - Global variables with thread-safe access
- ๐ Drools Compatibility - ~97% Drools parity
See Release Notes โ | CLIPS Features Guide โ
๐ Key Features
Native Engine
- GRL Support - Full Grule-compatible syntax
- Function Calls in WHEN - Call functions directly in conditions (NEW in v0.10.0)
- Plugin System - 44+ actions, 33+ functions
- Knowledge Base - Centralized rule management
- Type Safety - Rust's compile-time guarantees
- Production Ready - REST API, monitoring, health checks
Backward Chaining Engine โ PRODUCTION READY (v1.1.0)
- ๐ 100-1000x Performance - O(1) conclusion index vs O(n) linear search
- ๐ฏ Goal-Driven Reasoning - Work backwards from goals to prove them (88% complete)
- ๐ Expression Parser - Full AST-based boolean logic (<20ยตs parsing)
- ๐งฉ Variable Unification - Pattern matching with conflict detection
- ๐ Search Strategies - Depth-first, breadth-first, iterative deepening
- ๐ Proof Traces - Track reasoning chains and statistics
- โ Comprehensive Testing - 39 unit tests + 15 examples + 9 benchmarks
- ๐ Complete Documentation - 5 comprehensive guides
RETE-UL Engine (Recommended for 50+ rules)
- ๐ High Performance - Efficient RETE algorithm with incremental updates
- ๐ฅ RETE Algorithm - Advanced pattern matching with good Drools compatibility
- ๐ Multi-field Variables - Array/collection pattern matching with 9 operations (v0.17.0)
- ๐งฎ Expression Evaluation - Runtime arithmetic expressions (+, -, *, /, %) (v0.16.0)
- ๐ Chained Expressions - Values from previous rules available to subsequent rules (v0.16.0)
- ๐งฎ Accumulate Functions - sum, count, average, min, max aggregations (v0.13.4)
- ๐ Variable Comparison - Compare fact fields dynamically (L1 > L1Min) (v0.13.4)
- ๐๏ธ Retract - Remove facts from working memory (v0.14.1)
- ๐ Thread-Safe - Send + Sync for multi-threaded use (v0.15.0)
- ๐ Template System - Type-safe structured facts (v0.10.0)
- ๐ Defglobal - Global variables across firings (v0.10.0)
- ๐ฆ Deffacts - Initial fact definitions (v0.11.0)
- ๐งช Test CE - Arbitrary boolean expressions in rules (v0.12.0)
- โก Conflict Resolution - 8 CLIPS strategies (Salience, LEX, MEA, etc.) (v0.13.0)
- ๐ง Truth Maintenance System (TMS) - Automatic fact retraction and dependency tracking (v0.16.0)
- Logical Assertions - Facts derived by rules are auto-retracted when premises become invalid
- Justifications - Track why facts exist (explicit user input vs. derived by rules)
- Cascade Retraction - Automatically retract dependent facts when base facts are removed
- CLIPS-Compatible -
logicalAssert()API for derived facts
- ๐ฏ Incremental Updates - Only re-evaluate affected rules
- ๐ง Working Memory - FactHandles with insert/update/retract
- ๐ Variable Binding - Cross-pattern $var syntax
- ๐พ Memoization - Efficient caching for repeated evaluations
Choose Your Engine:
- Forward Chaining (data-driven):
- < 10 rules โ Native Engine (simpler API, plugin support)
- 10-50 rules โ Either (RETE ~2x faster)
- 50+ rules โ RETE-UL Engine (2-24x faster, highly recommended)
- Backward Chaining (goal-driven) ๐:
- Any rule count โ Backward Engine (100-1000x faster with O(1) index)
- Ideal for: Diagnostics, expert systems, decision trees
- Scales to: 10,000+ rules efficiently
- Both needs โ Hybrid approach (combine forward + backward)
๐ Performance: RETE shows 2-24x improvement; Backward shows 100-1000x improvement!
๐ Engine Comparison Guide โ | Quick Start Guide โ
๐ฆ Installation
[]
= "1.1.0"
Optional Features
# Enable backward chaining (Production Ready! ๐)
= { = "1.1.0", = ["backward-chaining"] }
# Enable streaming support
= { = "1.1.0", = ["streaming"] }
# Enable all features
= { = "1.1.0", = ["backward-chaining", "streaming"] }
๐ Migrating to v0.18.0
Breaking Change: Action Closure Signature
v0.18.0 introduces a breaking change to fix critical bugs in action execution.
Who is Affected?
โ
GRL Files - NOT AFFECTED - No changes needed!
โ Programmatic Rules - If you create rules with TypedReteUlRule, update your closures.
Migration Steps
Step 1: Add Import
use ActionResults;
Step 2: Update Closure Signature
// โ Before v0.18.0
let action = new;
// โ
After v0.18.0
let action = new;
๐ฏ Quick Start
Option 1: Native Engine (Simple & Plugin-rich)
use ;
GRL Rule Example (rules/discount.grl):
rule "GoldCustomerDiscount" salience 10 {
when
customer.tier == "gold" && order.amount > 1000
then
order.discount = order.amount * 0.15;
Log("Applied 15% gold customer discount");
}
Option 2: RETE-UL Engine (High Performance)
use ;
๐งฎ NEW: Accumulate Functions (v0.13.4)
Powerful aggregation capabilities for calculating metrics across multiple facts!
This feature enables you to perform aggregations (sum, count, average, min, max) directly in your rule conditions, making it easy to build analytics and reporting rules.
โจ Built-in Accumulate Functions
// 5 Ready-to-Use Functions
sum // Add up numeric values
count // Count matching facts
average // Calculate mean
min // Find minimum value
max // Find maximum value
๐ Real-World Example: Sales Analytics
Business Scenario: E-commerce platform needs to automatically detect high-value sales periods and trigger inventory allocation.
Rust Implementation:
use *;
use FactValue;
// Sample order amounts
let orders = vec!;
// Calculate total revenue
let sum_fn = SumFunction;
let mut state = sum_fn.init;
for amount in &orders
let total = state.get_result; // Float(9000.0)
// Business rule: If total > $8000, trigger alert
if let Float = total
๐ฏ Future GRL Syntax (Coming Soon)
When integrated with GRL parser, you'll be able to write:
rule "HighSalesAlert" {
when
$total: accumulate(
Order($amount: amount, status == "completed"),
sum($amount)
)
$total > 8000
then
Alert.send("High-value sales period!");
Inventory.allocate_extra();
}
rule "AverageOrderValue" {
when
$avg: accumulate(
Order($amount: amount),
average($amount)
)
$avg > 1000
then
Customer.offerPremiumMembership();
}
๐ All Accumulate Functions
1. SUM - Total Revenue
let mut sum_state = SumFunction.init;
for order in orders
// Result: Float(total_revenue)
2. COUNT - Number of Orders
let mut count_state = CountFunction.init;
for order in orders
// Result: Integer(order_count)
3. AVERAGE - Mean Order Value
let mut avg_state = AverageFunction.init;
for order in orders
// Result: Float(average_value)
4. MIN - Smallest Order
let mut min_state = MinFunction.init;
for order in orders
// Result: Float(minimum_value)
5. MAX - Largest Order
let mut max_state = MaxFunction.init;
for order in orders
// Result: Float(maximum_value)
๐ง Custom Accumulate Functions
Create your own accumulate functions by implementing the trait:
use *;
// Custom function: Collect all values
;
๐งช Complete Examples
See working examples:
- accumulate_demo.rs - Basic accumulate functions
- accumulate_rete_integration.rs - E-commerce analytics
๐ Variable-to-Variable Comparison (v0.13.4)
The RETE-UL engine now supports comparing variables directly with each other!
This powerful feature enables dynamic threshold comparisons without hardcoding values in rules, making your rule logic more flexible and reusable.
โจ Why Variable Comparison?
Traditional Approach (Hardcoded):
rule "CheckAge" {
when customer.age > 18 // Hardcoded threshold
then customer.eligible = true;
}
New Approach (Dynamic):
rule "CheckAge" {
when customer.age > settings.minAge // Dynamic threshold
then customer.eligible = true;
}
๐ Real-World Example: Product Eligibility
Business Scenario: FamiCanxi product requires customers to meet dynamic thresholds for L1 and CM2 scores that can vary based on market conditions.
GRL Rule (famicanxi_rules.grl):
rule "FamiCanxi Product Eligibility Rule" salience 50 {
when
(Facts.L1 > Facts.L1Min) &&
(Facts.CM2 > Facts.Cm2Min) &&
(Facts.productCode == 1)
then
Facts.levelApprove = 1;
}
RETE-UL Implementation:
use ;
๐ฏ Key Benefits
- Dynamic Business Rules - Change thresholds without modifying rule code
- A/B Testing - Test different threshold configurations easily
- Multi-Tenant Support - Different thresholds per customer/region
- Configuration-Driven - Rules adapt to configuration changes
- Reduced Code Duplication - One rule handles multiple scenarios
๐ Supported Comparisons
// Numeric comparisons
Facts.value > Facts.threshold
Facts.value >= Facts.minimum
Facts.value < Facts.maximum
Facts.value <= Facts.limit
Facts.value == Facts.target
Facts.value != Facts.excluded
// Mixed: variable with constant
Facts.value > Facts.threshold && Facts.status == "active"
// Multiple variable comparisons
(Facts.minValue < Facts.value) && (Facts.value < Facts.maxValue)
๐งช Test Examples
See complete working examples:
- famicanxi_rete_test.rs - RETE-UL engine with variable comparison
- famicanxi_grl_test.rs - Standard engine with GRL
- test_variable_comparison.rs - Comprehensive test suite
๐ง Truth Maintenance System (TMS)
v0.16.0 introduces automatic dependency tracking and cascade retraction!
The Truth Maintenance System (TMS) automatically tracks why facts exist and removes derived facts when their premises become invalid. This is similar to CLIPS' logical assertions.
โจ Why TMS?
Problem Without TMS:
// Rule derives Gold status from high spending
rule "Upgrade to Gold"
// Later, spending drops below threshold
customer.totalSpent = 5000;
// โ GoldStatus fact still exists! Manual cleanup needed.
Solution With TMS:
// Rule uses logical assertion
rule "Upgrade to Gold"
// Later, spending drops below threshold
customer.totalSpent = 5000;
// โ
GoldStatus automatically retracted by TMS!
๐ฏ Key Concepts
1. Explicit vs Logical Facts
-
Explicit Facts: Inserted by user code, persist until manually retracted
engine.insert; // Explicit -
Logical Facts: Derived by rules, auto-retracted when premises invalid
engine.insert_logical;
2. Justifications
Each fact has one or more justifications explaining why it exists:
- Explicit Justification: "User inserted this fact"
- Logical Justification: "Rule X derived this from facts Y and Z"
3. Cascade Retraction
When a premise fact is retracted, all facts logically derived from it are automatically retracted:
Customer(id=1, spent=15000) โโโ
โโโ> GoldStatus(customer=1) โโ> FreeShipping(customer=1)
โ
Rule: "Upgrade to Gold" โโโโโโโ
// Retract Customer
engine.retract(customer_handle);
// โ
Automatically retracts:
// - GoldStatus (derived from Customer)
// - FreeShipping (derived from GoldStatus)
๐ Real-World Example: Customer Tier Management
Business Scenario: E-commerce platform automatically manages customer tiers based on spending. When spending changes, tier status should update automatically.
Implementation:
use ;
๐ TMS API
// Logical assertion (auto-retract when premises invalid)
let handle = engine.insert_logical;
// Explicit assertion (manual lifecycle)
let handle = engine.insert_explicit;
// Get TMS statistics
let stats = engine.tms.stats;
println!;
println!;
// Query justifications for a fact
if let Some = engine.tms.get_justifications
๐ฏ Best Practices
-
Use Logical Assertions for Derived Facts
- Facts calculated from other facts should be logical
- E.g., tier status, discount eligibility, recommendations
-
Use Explicit Assertions for Base Facts
- User input, external data should be explicit
- E.g., customer profiles, orders, transactions
-
Track Premises Correctly
- Pass all fact handles used in rule's WHEN clause
- Ensures proper cascade retraction
-
Monitor TMS Statistics
- Check for memory leaks (orphaned justifications)
- Verify cascade behavior in tests
๐ง Function Calls in WHEN Clause
v0.10.0 introduces the ability to call functions directly in rule conditions!
โจ Before (Rule Chaining)
rule "Step1: Call AI" {
when Customer.needsCheck == true
then set(Customer.sentiment, aiSentiment(Customer.feedback));
}
rule "Step2: Check Result" {
when Customer.sentiment == "negative"
then Alert("Negative feedback detected!");
}
โจ After (Direct Function Calls)
rule "Check Sentiment" {
when aiSentiment(Customer.feedback) == "negative"
then Alert("Negative feedback detected!");
}
๐ Use Cases
AI/ML Integration:
rule "Fraud Detection" {
when aiFraud(Transaction.amount, Transaction.userId) == true
then set(Transaction.status, "blocked");
}
Business Logic:
rule "Credit Check" {
when creditScore(Customer.id) > 750
then set(Customer.tier, "premium");
}
Data Validation:
rule "Email Validation" {
when validateEmail(User.email) == false
then set(User.error, "Invalid email format");
}
See ai_functions_in_when.rs for complete examples!
๐ Documentation
๐ Getting Started
- Quick Start Guide - Choose and use your engine
- Engine Comparison - Native vs RETE-UL decision guide
- Examples - 30+ working examples
๐ง Core Features
- Features Guide - All engine features explained
- Plugin System - Built-in plugins & custom creation
- Advanced Usage - Complex patterns & workflows
- AI Integration - ML models & LLM integration
๐ RETE-UL Engine
- RETE Guide - Complete RETE-UL documentation
- CLIPS Features - Template System & Defglobal
- CLIPS Analysis - Feature comparison & roadmap
๐ Distributed & Production
- Streaming Engine - Real-time stream processing
- Distributed Setup - Getting started with distributed mode
- Distributed Architecture - Cluster setup & scaling
- Distributed Features - Complete distributed guide
- Performance Guide - Benchmarks & optimization
๐ Reference
- API Reference - Complete API documentation
- GRL Syntax - Rule language reference
- Roadmap - Future plans & upcoming features
- Release Notes - What's new in v0.10.0
- Changelog - Complete changelog
๐ฅ๏ธ VS Code Extension
Install GRL Syntax Highlighting for .grl files:
Features:
- Syntax highlighting for GRL
- Snippets for rules, actions, functions
- Auto-detection of
.grlfiles
Install: Search grl-syntax-highlighting in VS Code Extensions
๐ฏ Use Cases
1. Business Rules Engine
// Pricing, discounts, loyalty programs
rule "VIPDiscount"
2. Dynamic Eligibility & Thresholds (NEW!)
// Product eligibility with dynamic thresholds
rule "ProductEligibility" {
when (customer.score > settings.minScore) &&
(customer.income > settings.minIncome) &&
(customer.age >= settings.minAge)
then customer.eligible = true;
}
// Credit limit based on dynamic risk assessment
rule "CreditLimit" {
when (customer.creditScore > risk.threshold) &&
(customer.debtRatio < risk.maxDebtRatio)
then customer.creditLimit = customer.income * risk.multiplier;
}
3. Fraud Detection
// Real-time fraud scoring
rule "HighRiskTransaction"
4. Workflow Automation
// Multi-step approval workflows
rule "ManagerApproval" agenda-group "approvals"
5. Real-Time Systems
// IoT, monitoring, alerts
rule "TemperatureAlert"
More examples: examples/ directory
โก Performance
RETE-UL Engine Benchmarks
- Pattern Matching: ~4ยตs per fact insertion (1000 facts)
- Incremental Updates: 2x speedup (only affected rules)
- Memoization: 99.99% cache hit rate
- Template Validation: 1-2ยตs per fact
- Global Variables: 120ns read, 180ns write
Native Engine Benchmarks
- Rule Execution: ~10ยตs per rule (simple conditions)
- Plugin Actions: ~2-5ยตs per action call
- Facts Access: O(1) HashMap lookups
Comparison: Performance Guide
Automated GRL Test Harness
This repository includes a lightweight, data-driven test harness used to exercise the GRL examples in examples/rules and verify they still parse and run against the engine.
Purpose:
- Provide end-to-end coverage for
.grlexample files without requiring full production action implementations. - Detect regressions in the parser, engine, and example rules.
Where to find it:
tests/grl_harness_data.rsโ the primary data-driven harness. It readstests/grl_cases.yml, constructsFacts, loads the.grlfile(s), builds aKnowledgeBase, registers lightweight action handlers and functions, executes the engine, and performs simple assertions.tests/grl_harness.rsโ smaller smoke tests used by the harness and examples.tests/grl_cases.ymlโ YAML-driven cases. Each case points at a.grlfile and providesinitial_factsand optionalexpectchecks.
Why it uses minimal action handlers:
Many GRL samples call custom actions (e.g., apply_discount, sendAlert, setEcoMode, etc.). To exercise the rules end-to-end without requiring external systems, the harness registers small, no-op or fact-mutating action handlers. These handlers are only for testing and live in tests/grl_harness_data.rs.
How to run the harness (local development / CI):
# from repository root (zsh)
What to look for:
- The harness prints a per-case log (e.g., "=== Running case: fraud_detection ===") and a small set of logs generated by the registered handlers and functions.
- Each case prints the number of rules fired. The harness currently performs lightweight assertions (e.g., rules fired, and simple fact field checks) โ see
tests/grl_harness_data.rsfor details.
How to add or update cases:
- Add a new case to
tests/grl_cases.ymlwith fields:name,grl,initial_facts, and optionalexpect. - If the
.grluses custom actions not yet covered, either:- Add a small test handler in
tests/grl_harness_data.rs(follow the existing pattern), or - Add sufficient
initial_factsso rules can be exercised without that action being mandatory.
- Add a small test handler in
- Run the harness and verify the new case behaves as expected.
Notes & next improvements:
- The harness currently registers many minimal handlers to unblock rule execution; a future iteration should replace no-ops with tighter, case-specific assertions so the tests verify meaningful behavior instead of only successful execution.
- There are some compiler warnings in the codebase (missing docs, unused-variable warnings). These do not block tests but can be cleaned up to keep CI logs tidy.
Questions or contributions: If you'd like, I can (a) strengthen per-case assertions, (b) consolidate test handlers into helpers, or (c) add a GitHub Actions workflow to run the harness in CI.
๐ค Contributing
We welcome contributions! See CONTRIBUTING.md for guidelines.
Development Setup
# Clone repository
# Run tests
# Run examples
# Build documentation
๐ License
This project is licensed under the MIT License - see LICENSE file.
๐ Acknowledgments
Inspired by:
- Drools - JBoss Rule Engine
- CLIPS - NASA C Language Integrated Production System
- Grule - Go Rule Engine
Special Thanks:
- Rust community for amazing tools and libraries
- Contributors who helped improve the engine
- Users providing valuable feedback
๐ Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Email: ttvuhm@gmail.com
๐ Stats
Made with โค๏ธ by Ton That Vu