Rust Rule Engine v1.19.0 ๐ฆโก๐
A blazing-fast production-ready rule engine for Rust supporting both Forward and Backward Chaining. Features RETE-UL algorithm with Alpha Memory Indexing and Beta Memory Indexing, parallel execution, goal-driven reasoning, and GRL (Grule Rule Language) syntax.
๐ v1.19.0: Added in operator for array membership checks and fixed string methods (startsWith, endsWith) in GRL parser. Now supports concise syntax like User.role in ["admin", "moderator"] and File.name endsWith ".jpg". All 154 tests pass!
๐ 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), tumbling (non-overlapping), and session (gap-based) ๐
- 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.19.0 ๐
๐ฏ Array Membership Operator (in)
Concise syntax for checking if a value exists in an array!
// OLD WAY - Verbose with multiple OR conditions
rule "SkipDependencies"
// NEW WAY - Clean and maintainable โจ
rule "SkipDependencies"
Features:
- โ
Array literals:
["value1", "value2", 123, true] - โ Mixed types: strings, numbers, booleans
- โ Works with RETE and backward chaining
- โ
Example:
cargo run --example in_operator_demo
๐ค String Methods Fixed (startsWith, endsWith)
Previously missing from GRL parser, now fully supported!
rule "AdminEmail"
rule "ImageFile"
All String Operators:
- โ
startsWith- Check prefix - โ
endsWith- Check suffix - โ
contains- Substring search - โ
matches- Wildcard patterns (*and?) - โ
Example:
cargo run --example string_methods_demo
โจ Previous Release: v1.17.0
๐ Proof Graph Caching with TMS Integration
Global cache for proven facts with dependency tracking and automatic invalidation for backward chaining!
Key Features
1. Proof Caching
- Cache proven facts with their justifications (rule + premises)
- O(1) lookup by fact key (predicate + arguments)
- Multiple justifications per fact (different ways to prove)
- Thread-safe concurrent access with Arc<Mutex<>>
2. Dependency Tracking
- Forward edges: Track which rules used a fact as premise
- Reverse edges: Track which facts a fact depends on
- Automatic dependency graph construction during proof
3. TMS-Aware Invalidation
- Integrates with RETE's IncrementalEngine insert_logical
- When premise retracted โ cascading invalidation through dependents
- Recursive propagation through entire dependency chain
- Statistics tracking (hits, misses, invalidations, justifications)
4. Search Integration
- Seamlessly integrated into DepthFirstSearch and BreadthFirstSearch
- Cache lookup before condition evaluation (early return on hit)
- Automatic cache updates via inserter closure
Usage Example
use ;
use IncrementalEngine;
// Create engines
let mut rete_engine = new;
let kb = /* load rules */;
let mut backward_engine = new;
// Create search with ProofGraph enabled
let search = new_with_engine;
// First query builds cache
let result1 = backward_engine.query_with_search?;
// Subsequent queries use cache
let result2 = backward_engine.query_with_search?;
Dependency Tracking Example
// Given rules: A โ B โ C (chain dependency)
let result_c = engine.query?; // Proves A, B, C
// Retract A (premise)
facts.set;
// Automatic cascading invalidation:
// A invalidated โ B invalidated โ C invalidated
// Total: 3 invalidations propagated through dependency graph
Multiple Justifications Example
// Same fact proven 3 different ways:
// Rule 1: HighSpender โ eligible
// Rule 2: LoyalCustomer โ eligible
// Rule 3: Subscription โ eligible
let result = engine.query?;
// ProofGraph stores all 3 justifications
// If one premise fails, others still valid!
Try it yourself:
# Run comprehensive demo with 5 scenarios
# Run integration tests
New Files:
src/backward/proof_graph.rs(520 lines) - Core ProofGraph implementationtests/proof_graph_integration_test.rs- 6 comprehensive testsexamples/09-backward-chaining/proof_graph_cache_demo.rs- Interactive demo
Features:
- โ Global proof caching with O(1) lookup
- โ Dependency tracking (forward + reverse edges)
- โ TMS-aware cascading invalidation
- โ Multiple justifications per fact
- โ Thread-safe concurrent access
- โ Statistics tracking (hits/misses/invalidations)
- โ Zero overhead when cache miss
- โ Automatic integration with DFS/BFS search
โจ What's New in v1.18.28 ๐
๐ง Dependency Updates & Bug Fixes
Critical Unicode Bug Fix - Upgraded to rexile 0.5.3 with complete Unicode support!
Changes
1. Rexile Upgrade (0.4.10 โ 0.5.3)
- โ CRITICAL FIX: Unicode char boundary panic resolved
- โ GRL files with Unicode symbols (โ, โ, โซ, emojis, CJK) now work perfectly
- โ No performance regression - benchmarks stable
- โ ๏ธ Skipped 0.5.1 & 0.5.2 due to critical Unicode bugs
2. Nom Parser Upgrade (7.x โ 8.0)
- โ
Removed deprecated
tuplecombinator - โ
Updated to modern nom 8.0 API with
Parsertrait - โ
Changed from
parser(input)?toparser.parse(input)? - โ All stream syntax parsing updated
3. Criterion Benchmark Updates
- โ
Replaced deprecated
criterion::black_boxwithstd::hint::black_box - โ Updated all 6 benchmark files
- โ Modern Rust stdlib usage (no external deps for black_box)
Verification
All Systems Green:
- โ 152/152 tests passing (100% pass rate)
- โ All 29 examples working (including Unicode-heavy examples)
- โ All benchmarks passing with stable performance
- โ Zero regressions detected
Unicode Test Cases:
// These now work perfectly in v1.18.28:
// Rule: Amount < 2M + COD โ Auto approve โ
// Mathematical: โ โซ โ โ โ โ โ
// Emoji: ๐ ๐ โ
โ โ
// CJK: ่งๅ (Chinese characters) โ
Performance
No regression from previous version:
- Alpha Linear 1K: ~18.0ยตs (stable)
- Alpha Indexed 1K: ~147ns (stable)
- Speedup: ~122x (maintained)
Recommendation: โ Safe to upgrade - Critical Unicode fixes with zero breaking changes!
โจ What's New in v1.18.27 ๐
โก Performance Upgrade - Rexile 0.4.10
Major performance improvements - Upgraded to rexile 0.4.10 with significant optimizations.
Performance Gains:
- ๐ Alpha Linear 10K: 13.8% faster (7.95ms โ 6.85ms)
- ๐ Alpha Linear 50K: 25% faster (validated with stable benchmarks)
- ๐ Beta Nested Loop 1K: 9.8% faster (119ms โ 108ms)
- ๐ Token Pooling 100K: 7.7% faster (3.28ms โ 3.02ms)
- โก Beta Indexing: Maintains exceptional 180-815x speedup over linear scan
What Changed:
- Expression evaluation optimized for small-to-medium workloads (1K-10K items)
- Improved memory access patterns for indexed lookups
- Enhanced token pooling efficiency
- Better linear scanning performance
Benchmarking:
- Use
./bench_stable.shfor reliable performance measurements - See
REXILE_0.4.10_PERFORMANCE_COMPARISON.mdfor detailed analysis - See
BENCHMARK_VARIANCE_ANALYSIS.mdfor stability testing methodology
Verdict: โ Strongly recommended upgrade - Real performance improvements across all common workloads with no significant regressions.
โจ What's New in v1.18.26 ๐
๐ Migrated from regex to rexile crate
Lighter regex implementation - Replaced regex crate with rexile for pattern matching.
Why rexile?
- ๐ชถ Lighter weight - Smaller binary footprint
- ๐ฏ Simpler API - Direct
&straccess from captures - โ Full compatibility - All 551 tests pass, all examples work
API Changes (internal):
// Before (regex)
use Regex;
let re = new.unwrap;
let value = caps.get.unwrap.as_str;
// After (rexile)
use Pattern;
let re = new.unwrap;
let value = ∩︀ // Direct &str access!
Final Core Dependencies: Only 7 essential crates
chrono, log, nom, rexile, serde, serde_json, thiserror
โจ What's New in v1.16.1
๐งน Minimal Dependencies - Pure Stdlib
Removed 5 external dependencies - replaced with Rust stdlib or removed dead code:
Replaced with stdlib:
- โ
num_cpusโ โstd::thread::available_parallelism()(Rust 1.59+) - โ
once_cellโ โstd::sync::OnceLock(Rust 1.70+) - โ
fastrandโ โstd::collections::hash_map::RandomState
Removed unused:
- โ
petgraph- Declared but never used (zero code references) - โ
futures- Declared but never used (tokio is sufficient)
Benefits:
- ๐ฆ 5 fewer crates - down from 12 to 7 core dependencies (41% reduction!)
- ๐ก๏ธ More reliable - 100% stdlib for threading, lazy init, randomization
- โก Zero performance regression - all benchmarks unchanged
- ๐ง Modern Rust - using latest stdlib features
Final Core Dependencies: Only 7 essential crates
chrono, log, nom, rexile, serde, serde_json, thiserror
Optional dependencies (by feature):
tokio- Async runtime for streamingredis- State backend for streaming-redis
Code changes:
- Thread detection:
num_cpus::get()โstd::thread::available_parallelism() - Lazy patterns (20 patterns):
once_cell::Lazyโstd::sync::OnceLock - Random generation:
fastrandโRandomState::new().build_hasher() - Fixed flaky test in session window eviction
Testing:
- โ All 428+ tests passing
- โ All 14+ examples working
- โ All features validated (streaming, backward-chaining, etc.)
โจ What's New in v1.16.0
๐ช Session Windows for Stream Processing
Complete implementation of session-based windowing for real-time event streams! Session windows dynamically group events based on inactivity gaps rather than fixed time boundaries.
What are Session Windows?
Unlike sliding or tumbling windows, session windows adapt to natural event patterns:
Events: A(t=0), B(t=1), C(t=2), [gap 10s], D(t=12), E(t=13)
Timeout: 5 seconds
Result:
Session 1: [A, B, C] - ends when gap > 5s
Session 2: [D, E] - starts after gap > 5s
GRL Syntax:
rule "UserSessionAnalysis" {
when
activity: UserAction from stream("user-activity")
over window(5 min, session)
then
AnalyzeSession(activity);
}
Rust API:
use ;
use WindowType;
use Duration;
let window = WindowSpec ;
let mut node = new;
Perfect for:
- ๐ User Session Analytics - Track natural user behavior sessions
- ๐ Cart Abandonment - Detect when users don't complete checkout
- ๐ Fraud Detection - Identify unusual session patterns
- ๐ก IoT Sensor Grouping - Group burst events from sensors
Features:
- โ Automatic session boundary detection based on inactivity
- โ Dynamic session sizes (adapts to activity patterns)
- โ O(1) event processing with minimal overhead
- โ Full integration with RETE network
- โ 7 comprehensive tests (all passing)
- โ
Interactive demo:
cargo run --example session_window_demo --features streaming
โจ What's New in v1.15.1
๐งน Codebase Cleanup
Major cleanup and optimization of the project structure for better maintainability and developer experience!
๐ง Dependencies Optimized (-75% dev-deps)
- Removed 9 unused dev-dependencies (axum, tower, reqwest, tracing, etc.)
- Eliminated duplicate dependencies (serde, chrono already in main deps)
- Kept only essentials: criterion, tokio, serde_yaml
- Faster build times and smaller binary size
Benefits:
- โก Faster compilation and CI runs
- ๐ Easier onboarding with clear example structure
- ๐งน Less code to maintain (-76% examples)
- โ Production-ready with all tests passing
โจ What's New in v1.15.0
โ Array Append Operator (+=)
Added support for the += operator to append values to arrays in GRL actions! This is particularly useful for building recommendation lists, accumulating results, and managing collections.
GRL Syntax:
rule "Product Recommendation" salience 100 no-loop {
when
ShoppingCart.items contains "Laptop" &&
!(Recommendation.items contains "Mouse")
then
Recommendation.items += "Mouse"; // Append to array
Recommendation.items += "USB-C Hub"; // Multiple appends
Log("Added recommendations");
}
Rust Usage:
use ;
use GrlReteLoader;
let mut engine = new;
load_from_file?;
let mut facts = new;
facts.set;
facts.set;
engine.insert_typed_facts;
engine.fire_all;
// Result: Recommendation.items = ["Mouse", "USB-C Hub"] โ
Integration with Rule Mining:
The += operator works seamlessly with rust-rule-miner for automatic rule generation:
// Mine association rules from historical data
let rules = miner.mine_association_rules?;
// Export to GRL with += syntax
let grl = to_grl;
// Generates: Recommendation.items += "Phone Case";
// Load and execute in RETE engine
load_from_string?;
Supported Everywhere:
- โ Forward chaining (RETE engine)
- โ Backward chaining (goal-driven reasoning)
- โ Parallel execution
- โ All action execution contexts
๐ 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
- RETE Optimization - 1,235x join speedup & memory optimizations (v1.13.0+)
- RETE Benchmarks - Real performance data & analysis (v1.13.0+)
- 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 โ
๐ Older Releases
See CHANGELOG.md for full version history (v0.1.0 - v0.19.0).