# Rust Rule Engine v0.13.0 π¦β‘
[](https://crates.io/crates/rust-rule-engine)
[](https://docs.rs/rust-rule-engine)
[](https://opensource.org/licenses/MIT)
[](https://github.com/KSD-CO/rust-rule-engine/actions)
A high-performance rule engine for Rust with **RETE-UL algorithm**, **CLIPS-inspired features**, **Plugin System**, and **GRL (Grule Rule Language) support**. Designed for production use with good Drools compatibility.
---
## β¨ What's New in v0.13.0
β‘ **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
### 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
[**See Test CE Demo β**](examples/test_ce_comprehensive.rs)
### 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
[**See Deffacts Demo β**](examples/rete_deffacts_demo.rs)
### 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
[**See Benchmark Results β**](BENCHMARK_RESULTS.md)
### 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 β**](RELEASE_v0.10.0.md) | [**CLIPS Features Guide β**](CLIPS_INSPIRED_FEATURES.md)
---
## π 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
### RETE-UL Engine (Recommended for 50+ rules)
- **π High Performance** - Efficient RETE algorithm with incremental updates
- **π₯ RETE Algorithm** - Advanced pattern matching with good Drools compatibility
- **π 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)*
- **π― 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:**
- **< 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)
- **Both needs** β Hybrid approach
π **Performance at 50 rules**: RETE shows good performance improvements over traditional engine!
π [**Engine Comparison Guide β**](ENGINE_COMPARISON.md) | [**Quick Start Guide β**](QUICK_START_ENGINES.md)
---
## π¦ Installation
```toml
[dependencies]
rust-rule-engine = "0.13.0"
```
### Optional Features
```toml
# Enable streaming support
rust-rule-engine = { version = "0.13.0", features = ["streaming"] }
```
---
## π― Quick Start
### Option 1: Native Engine (Simple & Plugin-rich)
```rust
use rust_rule_engine::{RustRuleEngine, Facts, Value};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create engine with plugins
let mut engine = RustRuleEngine::new();
engine.load_default_plugins()?;
// Load rules from GRL file
engine.load_rules_from_file("rules/discount.grl")?;
// Add facts
let mut facts = Facts::new();
facts.set("customer.tier", Value::String("gold".to_string()));
facts.set("order.amount", Value::Float(1500.0));
// Execute rules
engine.execute(&mut facts)?;
// Get result
println!("Discount: {}", facts.get("order.discount"));
Ok(())
}
```
**GRL Rule Example** (`rules/discount.grl`):
```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)
```rust
use rust_rule_engine::rete::{
IncrementalEngine, GrlReteLoader, TypedFacts, FactValue,
TemplateBuilder, FieldType
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut engine = IncrementalEngine::new();
// Optional: Define template for type safety
let order_template = TemplateBuilder::new("Order")
.required_string("order_id")
.float_field("amount")
.float_field("discount")
.build();
engine.templates_mut().register(order_template);
// Load rules from GRL
GrlReteLoader::load_from_file("rules/discount.grl", &mut engine)?;
// Insert facts with validation
let mut order = TypedFacts::new();
order.set("order_id", FactValue::String("ORD-001".to_string()));
order.set("amount", FactValue::Float(1500.0));
let handle = engine.insert_with_template("Order", order)?;
// Fire rules
engine.reset();
let fired = engine.fire_all();
println!("Fired {} rules", fired.len());
// Query results
if let Some(order) = engine.working_memory().get(&handle) {
println!("Discount: {:?}", order.data.get("discount"));
}
Ok(())
}
```
---
## π§ NEW: Function Calls in WHEN Clause
**v0.10.0 introduces the ability to call functions directly in rule conditions!**
### β¨ Before (Rule Chaining)
```grl
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)
```grl
rule "Check Sentiment" {
when aiSentiment(Customer.feedback) == "negative"
then Alert("Negative feedback detected!");
}
```
### π Use Cases
**AI/ML Integration:**
```grl
rule "Fraud Detection" {
when aiFraud(Transaction.amount, Transaction.userId) == true
then set(Transaction.status, "blocked");
}
```
**Business Logic:**
```grl
rule "Credit Check" {
when creditScore(Customer.id) > 750
then set(Customer.tier, "premium");
}
```
**Data Validation:**
```grl
rule "Email Validation" {
when validateEmail(User.email) == false
then set(User.error, "Invalid email format");
}
```
**See [ai_functions_in_when.rs](examples/ai_functions_in_when.rs) for complete examples!**
---
## π Documentation
### π Getting Started
- [**Quick Start Guide**](QUICK_START_ENGINES.md) - Choose and use your engine
- [**Engine Comparison**](ENGINE_COMPARISON.md) - Native vs RETE-UL decision guide
- [**Examples**](examples/) - 30+ working examples
### π§ Core Features
- [**Features Guide**](docs/FEATURES.md) - All engine features explained
- [**Plugin System**](docs/PLUGINS.md) - Built-in plugins & custom creation
- [**Advanced Usage**](docs/ADVANCED_USAGE.md) - Complex patterns & workflows
- [**AI Integration**](docs/REAL_AI_INTEGRATION.md) - ML models & LLM integration
### π RETE-UL Engine
- [**RETE Guide**](docs/RETE_GUIDE.md) - Complete RETE-UL documentation
- [**CLIPS Features**](CLIPS_INSPIRED_FEATURES.md) - Template System & Defglobal
- [**CLIPS Analysis**](CLIPS_FEATURES_ANALYSIS.md) - Feature comparison & roadmap
### π Distributed & Production
- [**Streaming Engine**](docs/STREAMING.md) - Real-time stream processing
- [**Distributed Setup**](docs/distributed_explained.md) - Getting started with distributed mode
- [**Distributed Architecture**](docs/distributed_architecture.md) - Cluster setup & scaling
- [**Distributed Features**](docs/distributed_features_guide.md) - Complete distributed guide
- [**Performance Guide**](docs/PERFORMANCE.md) - Benchmarks & optimization
### π Reference
- [**API Reference**](docs/API_REFERENCE.md) - Complete API documentation
- [**GRL Syntax**](docs/GRL_SYNTAX.md) - Rule language reference
- [**Roadmap**](docs/ROADMAP.md) - Future plans & upcoming features
- [**Release Notes**](RELEASE_v0.10.0.md) - What's new in v0.10.0
- [**Changelog**](CHANGELOG_v0.10.0.md) - Complete changelog
---
## π₯οΈ VS Code Extension
Install [GRL Syntax Highlighting](https://marketplace.visualstudio.com/items?itemName=tonthatvu.grl-syntax-highlighting) for `.grl` files:
**Features:**
- Syntax highlighting for GRL
- Snippets for rules, actions, functions
- Auto-detection of `.grl` files
**Install:** Search `grl-syntax-highlighting` in VS Code Extensions
---
## π― Use Cases
### 1. Business Rules Engine
```rust
// Pricing, discounts, loyalty programs
rule "VIPDiscount" {
when customer.points > 1000
then order.discount = 0.20;
}
```
### 2. Fraud Detection
```rust
// Real-time fraud scoring
rule "HighRiskTransaction" {
when transaction.amount > 10000 &&
transaction.location != customer.usual_location
then fraud.score = 0.85;
}
```
### 3. Workflow Automation
```rust
// Multi-step approval workflows
rule "ManagerApproval" agenda-group "approvals" {
when request.amount > 5000
then request.requires_manager = true;
}
```
### 4. Real-Time Systems
```rust
// IoT, monitoring, alerts
rule "TemperatureAlert" {
when sensor.temp > 80
then Alert.send("High temperature!");
}
```
**More examples:** [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](docs/PERFORMANCE.md)
---
## πΊοΈ Roadmap
### v0.13.0 (Current Release)
- [x] **Conflict Resolution Strategies** - 8 CLIPS strategies β
- **Target**: ~98% Drools compatibility
### v0.14.0 (Next Release - 2-3 weeks)
- [ ] **Multi-field Variables** - Array pattern matching
- [ ] **RETE Test CE Integration** - Test CE in RETE engine
- **Target**: ~99% Drools compatibility
### Future Features
- [ ] Truth Maintenance System (TMS)
- [ ] Module System for rule organization
- [ ] Backward Chaining support
- [ ] Interactive debugger
- [ ] Visual rule builder UI
[**Full Roadmap β**](docs/ROADMAP.md)
---
## π€ Contributing
We welcome contributions! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
### Development Setup
```bash
# Clone repository
git clone https://github.com/KSD-CO/rust-rule-engine.git
cd rust-rule-engine
# Run tests
cargo test
# Run examples
cargo run --example rete_template_globals_demo
# Build documentation
cargo doc --open
```
---
## π License
This project is licensed under the MIT License - see [LICENSE](LICENSE) file.
---
## π Acknowledgments
**Inspired by:**
- [Drools](https://www.drools.org/) - JBoss Rule Engine
- [CLIPS](https://www.clipsrules.net/) - NASA C Language Integrated Production System
- [Grule](https://github.com/hyperjumptech/grule-rule-engine) - 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](https://github.com/KSD-CO/rust-rule-engine/issues)
- **Discussions**: [GitHub Discussions](https://github.com/KSD-CO/rust-rule-engine/discussions)
- **Email**: ttvuhm@gmail.com
---
## π Stats



---
<div align="center">
**Made with β€οΈ by Ton That Vu**
</div>