Rust Rule Engine v0.13.4 ๐ฆโก
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.
๐ GitHub | Documentation | Crates.io
โจ What's New in v0.13.4
โก Variable-to-Variable Comparison in RETE - 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.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
RETE-UL Engine (Recommended for 50+ rules)
- ๐ High Performance - Efficient RETE algorithm with incremental updates
- ๐ฅ RETE Algorithm - Advanced pattern matching with good Drools compatibility
- ๐ Variable Comparison - Compare fact fields dynamically (L1 > L1Min) (v0.13.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)
- ๐ฏ 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 โ | Quick Start Guide โ
๐ฆ Installation
[]
= "0.13.4"
Optional Features
# Enable streaming support
= { = "0.13.4", = ["streaming"] }
๐ฏ 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: Variable-to-Variable Comparison (v0.13.0)
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
๐ง 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