Rust Rule Engine v1.12.0 ๐ฆโก๐
A blazing-fast production-ready rule engine for Rust supporting both Forward and Backward Chaining. Features RETE-UL algorithm, parallel execution, goal-driven reasoning, and GRL (Grule Rule Language) syntax.
๐ GitHub | Documentation | Crates.io
๐ฏ Reasoning Modes
๐ Forward Chaining (Data-Driven)
"When facts change, fire matching rules"
- Native Engine - Simple pattern matching for small rule sets
- RETE-UL - Optimized network for 100-10,000 rules with O(1) indexing
- Parallel Execution - Multi-threaded rule evaluation
Use Cases: Business rules, validation, reactive systems, decision automation
๐ฏ Backward Chaining (Goal-Driven)
"Given a goal, find facts/rules to prove it"
- Unification - Pattern matching with variable bindings
- Search Strategies - DFS, BFS, Iterative Deepening
- Aggregation - COUNT, SUM, AVG, MIN, MAX
- Negation - NOT queries with closed-world assumption
- Explanation - Proof trees with JSON/MD/HTML export
- Disjunction - OR patterns for alternative paths
- Nested Queries - Subqueries with shared variables
- Query Optimization - Automatic goal reordering for 10-100x speedup
Use Cases: Expert systems, diagnostics, planning, decision support, AI reasoning
๐ Stream Processing (Event-Driven) ๐
"Process real-time event streams with time-based windows"
- GRL Stream Syntax - Declarative stream pattern definitions
- StreamAlphaNode - RETE-integrated event filtering & windowing
- Time Windows - Sliding (continuous) and tumbling (non-overlapping)
- Multi-Stream Correlation - Join events from different streams
- WorkingMemory Integration - Stream events become facts for rule evaluation
Use Cases: Real-time fraud detection, IoT monitoring, financial analytics, security alerts, CEP
Example:
rule "Fraud Alert" {
when
login: LoginEvent from stream("logins") over window(10 min, sliding) &&
purchase: PurchaseEvent from stream("purchases") over window(10 min, sliding) &&
login.user_id == purchase.user_id &&
login.ip_address != purchase.ip_address
then
Alert.trigger("IP mismatch detected");
}
๐ Quick Start
Forward Chaining Example
use ;
let mut engine = new;
// Define rule in GRL
engine.add_rule_from_grl?;
// Add facts and execute
let mut facts = new;
facts.set;
engine.execute?;
// Result: Customer.Discount = 0.15 โ
Backward Chaining Example
use BackwardEngine;
let mut engine = new;
// Query: "Can this order be auto-approved?"
let result = engine.query?;
if result.provable
Stream Processing Example ๐
use parse_stream_pattern;
use ;
use WorkingMemory;
// Parse GRL stream pattern
let grl = r#"login: LoginEvent from stream("logins") over window(5 min, sliding)"#;
let = parse_stream_pattern?;
// Create stream processor
let mut node = new;
// Process events in real-time
let mut wm = new;
for event in event_stream
// Run: cargo run --example streaming_fraud_detection --features streaming
โจ What's New in v1.12.0 ๐
๐ Stream Processing Foundation!
GRL Stream Syntax - Parse and process real-time event streams with time-based windows!
๐ Stream Processing Features
GRL Stream Pattern Syntax:
// Stream with sliding window
login: LoginEvent from stream over window
// Stream with tumbling window
metric: MetricEvent from stream over window
// Simple stream without window
event: Event from stream
StreamAlphaNode - RETE Integration:
use parse_stream_pattern;
use ;
// Parse GRL pattern
let grl = r#"login: LoginEvent from stream("logins") over window(5 min, sliding)"#;
let = parse_stream_pattern?;
// Create stream processor
let mut node = new;
// Process events
if node.process_event
Real-World Example - Fraud Detection:
// 4 fraud detection rules implemented:
// 1. Suspicious IP changes (multiple IPs in 15 min)
// 2. High velocity purchases (>3 purchases in 15 min)
// 3. Impossible travel (location change too fast)
// 4. IP mismatch (login IP != purchase IP)
// Result: 7 alerts triggered from 16 events
cargo run --example streaming_fraud_detection --features streaming
Features Implemented:
- โ GRL stream syntax parser (nom-based, 15 tests)
- โ StreamAlphaNode for event filtering & windowing (10 tests)
- โ Sliding windows (continuous rolling)
- โ Tumbling windows (non-overlapping)
- โ WorkingMemory integration (stream โ facts)
- โ Duration units: ms, sec, min, hour
- โ Optional event type filtering
- โ Multi-stream correlation
Test Coverage:
- 58 streaming tests (100% pass)
- 8 integration tests (fraud, IoT, trading, security)
- 3 end-to-end tests (GRL โ RETE โ WorkingMemory)
- 2 comprehensive examples
โจ Previous Update - v1.11.0
๐ฏ Nested Queries & Query Optimization!
Complete Phase 1.1 with nested queries (subqueries) and intelligent query optimization for 10-100x performance improvements!
๐ Nested Queries
use *;
// Find grandparents using nested queries
let results = engine.query?;
// Complex eligibility with nested OR
query "CheckEligibility"
โก Query Optimization
// Enable optimization in GRL
query "OptimizedSearch"
// Manual optimization
let mut optimizer = new;
optimizer.set_selectivity; // 10% in stock
optimizer.set_selectivity; // 30% expensive
optimizer.set_selectivity; // 90% items
let optimized = optimizer.optimize_goals;
// Result: in_stock โ expensive โ item (10-100x faster!)
Performance Benefits:
- Before: 1000 items โ 900 expensive โ 270 in_stock = 2170 evaluations
- After: 10 in_stock โ 8 expensive โ 8 items = 26 evaluations
- Speedup: ~83x faster! ๐
New Features:
- Nested queries with WHERE clauses
- Query optimizer with goal reordering
- Selectivity estimation (heuristic & custom)
- Join order optimization
enable-optimizationflag in GRL- 19 new tests + 9 integration tests
Testing: 485/485 tests pass (368 unit + 117 integration) โข Zero regressions
๐ Nested Query Demo โข Optimizer Demo โข GRL Integration
๐ Documentation
Comprehensive documentation organized by topic:
๐ Getting Started
- Quick Start - Get up and running in 5 minutes
- Installation - Installation and setup guide
- Basic Concepts - Core concepts explained
- First Rules - Write your first rules
๐ฏ Core Features
- GRL Syntax - Grule Rule Language reference
- Features Overview - All engine capabilities
โก Advanced Features
- Streaming & CEP - Complex Event Processing
- Streaming Architecture - Deep dive into streaming
- Plugins - Custom plugins and extensions
- Performance - Optimization techniques
- Redis State - Distributed state management
๐ API Reference
- API Reference - Complete public API
- GRL Query Syntax - Backward chaining queries (v1.11.0+)
- Parser Cheat Sheet - Quick syntax reference
๐ Guides
- Backward Chaining Quick Start - Goal-driven reasoning
- RETE Integration - Combine forward + backward
- Module Management - Organize rules into modules
- Troubleshooting - Common issues and solutions
๐ก Examples
- AI Integration - Combine with ML models
๐ Full Documentation Index โ
โจ 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
Stream Processing Engine โ PRODUCTION READY (v1.4.0)
- ๐ 20+ Stream Operators - Fluent API for real-time data processing
- ๐ State Management - Memory, File, and Redis backends for distributed deployments
- โฑ๏ธ Watermark Support - Event-time processing with out-of-order handling
- ๐ช Windowing - Sliding, Tumbling, Session windows for time-based aggregations
- ๐ High Performance - 1M+ events/sec (Memory), 100k+ ops/sec (Redis)
- ๐ Built-in Aggregators - Count, Sum, Average, Min, Max with custom support
- ๐ Redis Integration - Distributed state with connection pooling and TTL
- ๐ฏ Late Data Handling - Drop, AllowedLateness, SideOutput, RecomputeWindows
- โ Comprehensive Testing - 21 unit tests + 5 comprehensive demos
- ๐ Complete Documentation - Architecture diagrams and production 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
- Stream Processing (real-time) ๐:
- Event streams โ Stream Processing Engine (1M+ events/sec)
- Ideal for: IoT monitoring, financial analytics, user behavior tracking
- Distributed: Redis backend for horizontal scaling
- Features: Windowing, watermarking, late data handling
- Both needs โ Hybrid approach (combine forward + backward + streaming)
๐ Performance: RETE shows 2-24x improvement; Backward shows 100-1000x improvement; Streaming handles 1M+ events/sec!
๐ Engine Comparison Guide โ | Quick Start Guide โ
๐ฆ Installation
[]
= "1.12.0"
Optional Features
# Enable backward chaining with negation support (Production Ready! ๐)
= { = "1.12.0", = ["backward-chaining"] }
# Enable streaming support (NEW in v1.12.0! ๐)
= { = "1.12.0", = ["streaming"] }
# Enable streaming with Redis backend (for distributed deployments)
= { = "1.12.0", = ["streaming", "streaming-redis"] }
# Enable all features
= { = "1.12.0", = ["backward-chaining", "streaming", "streaming-redis"] }
๐ 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.
๐ License
This project is licensed under the MIT License - see LICENSE file.
๐ Acknowledgments
๐ Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Email: ttvuhm@gmail.com
๐ Stats
Made with โค๏ธ by Ton That Vu