rust-rule-engine 0.10.1

A high-performance rule engine for Rust with RETE-UL algorithm (2-24x faster), CLIPS-inspired features (Template System, Defglobal), GRL support, and ~97% Drools compatibility
Documentation

Rust Rule Engine v0.10.1 πŸ¦€βš‘

Crates.io Documentation License: MIT Build Status

A high-performance rule engine for Rust with RETE-UL algorithm (2-24x faster), CLIPS-inspired features, Plugin System, and GRL (Grule Rule Language) support. Designed for production use with ~97% Drools compatibility.

πŸ”— GitHub | Documentation | Crates.io


✨ What's New in 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 β†’

Previous Updates (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)

  • πŸš€ 2-24x Faster - Proven benchmarks vs traditional engine (v0.10.1)
  • πŸ”₯ RETE Algorithm - High-performance pattern matching (~97% Drools parity)
  • πŸ“‹ Template System - Type-safe structured facts (v0.10.0)
  • 🌍 Defglobal - Global variables across firings (v0.10.0)
  • ⚑ Incremental Updates - Only re-evaluate affected rules
  • 🧠 Working Memory - FactHandles with insert/update/retract
  • 🎯 Advanced Agenda - Salience, activation groups, no-loop, max iterations guard
  • πŸ”— Variable Binding - Cross-pattern $var syntax
  • πŸ’Ύ Memoization - 99.99% cache hit rate

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: Traditional 1.72ms vs RETE 70Β΅s = 24.4x faster!

πŸ“– Engine Comparison Guide β†’ | Quick Start Guide β†’


πŸ“¦ Installation

[dependencies]
rust-rule-engine = "0.10.1"

Optional Features

# Enable streaming support
rust-rule-engine = { version = "0.10.1", features = ["streaming"] }

🎯 Quick Start

Option 1: Native Engine (Simple & Plugin-rich)

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):

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 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)

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

πŸ”§ Core Features

πŸš€ RETE-UL Engine

🌐 Distributed & Production

πŸ“‹ Reference


πŸ–₯️ VS Code Extension

Install 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

// Pricing, discounts, loyalty programs
rule "VIPDiscount" {
    when customer.points > 1000
    then order.discount = 0.20;
}

2. Fraud Detection

// Real-time fraud scoring
rule "HighRiskTransaction" {
    when transaction.amount > 10000 &&
         transaction.location != customer.usual_location
    then fraud.score = 0.85;
}

3. Workflow Automation

// Multi-step approval workflows
rule "ManagerApproval" agenda-group "approvals" {
    when request.amount > 5000
    then request.requires_manager = true;
}

4. Real-Time Systems

// IoT, monitoring, alerts
rule "TemperatureAlert" {
    when sensor.temp > 80
    then Alert.send("High temperature!");
}

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


πŸ—ΊοΈ Roadmap

v0.11.0 (Next Release - 2-3 weeks)

  • Deffacts - Initial fact definitions (CLIPS feature)
  • Test CE - Arbitrary conditions in patterns
  • Multi-field Variables - Array pattern matching
  • Target: ~98-99% Drools compatibility

v1.0.0 (Stable Release)

  • Full API stability guarantee
  • 99% Drools compatibility
  • Performance optimizations
  • Comprehensive benchmarks
  • Production hardening

Future Features

  • Truth Maintenance System (TMS)
  • Module System for rule organization
  • Backward Chaining support
  • Interactive debugger
  • Visual rule builder UI

Full Roadmap β†’


πŸ“Š Comparison with Other Engines

Feature Rust Engine Drools CLIPS
Performance ⚑ Excellent Good Excellent
Type Safety βœ… Compile-time ⚠️ Runtime ⚠️ Runtime
Memory Safety βœ… Guaranteed ❌ JVM ❌ Manual
RETE Algorithm βœ… RETE-UL βœ… Full RETE βœ… Full RETE
Pattern Matching βœ… Advanced βœ… Advanced βœ… Advanced
Plugin System βœ… Native ⚠️ Limited ❌ No
GRL Support βœ… Full N/A N/A
Template System βœ… v0.10.0 βœ… βœ…
Defglobal βœ… v0.10.0 βœ… βœ…
Drools Compatibility ~97% 100% ~60%
Learning Curve Medium High High
Ecosystem Growing Mature Mature

🀝 Contributing

We welcome contributions! See CONTRIBUTING.md for guidelines.

Development Setup

# 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 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


πŸ“ˆ Stats

GitHub stars GitHub forks Crates.io downloads


Made with ❀️ by Ton That Vu

⭐ Star us on GitHub | πŸ“¦ Download from Crates.io