rust-rule-engine 1.17.0

A blazing-fast Rust rule engine with RETE algorithm, backward chaining inference, and GRL (Grule Rule Language) syntax. Features: forward/backward chaining, pattern matching, unification, O(1) rule indexing, TMS, expression evaluation, method calls, streaming with Redis state backend, watermarking, and custom functions. Production-ready for business rules, expert systems, real-time stream processing, and decision automation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
# Rust Rule Engine v1.17.0 ๐Ÿฆ€โšก๐Ÿš€

[![Crates.io](https://img.shields.io/crates/v/rust-rule-engine.svg)](https://crates.io/crates/rust-rule-engine)
[![Documentation](https://docs.rs/rust-rule-engine/badge.svg)](https://docs.rs/rust-rule-engine)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Build Status](https://github.com/KSD-CO/rust-rule-engine/actions/workflows/rust.yml/badge.svg)](https://github.com/KSD-CO/rust-rule-engine/actions)

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.

๐Ÿ”— **[GitHub]https://github.com/KSD-CO/rust-rule-engine** | **[Documentation]https://docs.rs/rust-rule-engine** | **[Crates.io]https://crates.io/crates/rust-rule-engine**

---

## ๐ŸŽฏ 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:**
```grl
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
```rust
use rust_rule_engine::{RuleEngine, Facts, Value};

let mut engine = RuleEngine::new();

// Define rule in GRL
engine.add_rule_from_grl(r#"
    rule "VIP Discount" {
        when
            Customer.TotalSpent > 10000
        then
            Customer.Discount = 0.15;
    }
"#)?;

// Add facts and execute
let mut facts = Facts::new();
facts.set("Customer.TotalSpent", Value::Number(15000.0));
engine.execute(&mut facts)?;

// Result: Customer.Discount = 0.15 โœ“
```

### Backward Chaining Example
```rust
use rust_rule_engine::backward::BackwardEngine;

let mut engine = BackwardEngine::new(kb);

// Query: "Can this order be auto-approved?"
let result = engine.query(
    "Order.AutoApproved == true",
    &mut facts
)?;

if result.provable {
    println!("Order can be auto-approved!");
    println!("Proof: {:?}", result.proof_trace);
}
```

### Stream Processing Example ๐Ÿ†•
```rust
use rust_rule_engine::parser::grl::stream_syntax::parse_stream_pattern;
use rust_rule_engine::rete::stream_alpha_node::{StreamAlphaNode, WindowSpec};
use rust_rule_engine::rete::working_memory::WorkingMemory;

// Parse GRL stream pattern
let grl = r#"login: LoginEvent from stream("logins") over window(5 min, sliding)"#;
let (_, pattern) = parse_stream_pattern(grl)?;

// Create stream processor
let mut node = StreamAlphaNode::new(
    &pattern.source.stream_name,
    pattern.event_type,
    pattern.source.window.as_ref().map(|w| WindowSpec {
        duration: w.duration,
        window_type: w.window_type.clone(),
    }),
);

// Process events in real-time
let mut wm = WorkingMemory::new();
for event in event_stream {
    if node.process_event(&event) {
        // Event passed filters and is in window
        wm.insert_from_stream("logins".to_string(), event);
        // Now available for rule evaluation!
    }
}

// Run: cargo run --example streaming_fraud_detection --features streaming
```

---

## โœจ What's New in 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

```rust
use rust_rule_engine::backward::{BackwardEngine, DepthFirstSearch};
use rust_rule_engine::rete::IncrementalEngine;

// Create engines
let mut rete_engine = IncrementalEngine::new();
let kb = /* load rules */;
let mut backward_engine = BackwardEngine::new(kb);

// Create search with ProofGraph enabled
let search = DepthFirstSearch::new_with_engine(
    backward_engine.kb().clone(),
    Arc::new(Mutex::new(rete_engine)),
);

// First query builds cache
let result1 = backward_engine.query_with_search(
    "eligible(?x)",
    &mut facts,
    Box::new(search.clone()),
)?;

// Subsequent queries use cache 
let result2 = backward_engine.query_with_search(
    "eligible(?x)",
    &mut facts,
    Box::new(search),
)?;
```

#### Dependency Tracking Example

```rust
// Given rules: A โ†’ B โ†’ C (chain dependency)
let result_c = engine.query("C", &mut facts)?;  // Proves A, B, C

// Retract A (premise)
facts.set("A", FactValue::Bool(false));

// Automatic cascading invalidation:
// A invalidated โ†’ B invalidated โ†’ C invalidated
// Total: 3 invalidations propagated through dependency graph
```

#### Multiple Justifications Example

```rust
// Same fact proven 3 different ways:
// Rule 1: HighSpender โ†’ eligible
// Rule 2: LoyalCustomer โ†’ eligible  
// Rule 3: Subscription โ†’ eligible

let result = engine.query("eligible(?x)", &mut facts)?;

// ProofGraph stores all 3 justifications
// If one premise fails, others still valid!
```

**Try it yourself:**
```bash
# Run comprehensive demo with 5 scenarios
cargo run --example proof_graph_cache_demo --features backward-chaining

# Run integration tests
cargo test proof_graph --features backward-chaining
```

**New Files:**
- `src/backward/proof_graph.rs` (520 lines) - Core ProofGraph implementation
- `tests/proof_graph_integration_test.rs` - 6 comprehensive tests
- `examples/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.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, regex, serde, serde_json, thiserror
```

**Optional dependencies** (by feature):
- `tokio` - Async runtime for streaming
- `redis` - State backend for streaming-redis

**Code changes:**
- Thread detection: `num_cpus::get()` โ†’ `std::thread::available_parallelism()`
- Lazy regex (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:**
```grl
rule "UserSessionAnalysis" {
    when
        activity: UserAction from stream("user-activity")
            over window(5 min, session)
    then
        AnalyzeSession(activity);
}
```

**Rust API:**
```rust
use rust_rule_engine::rete::stream_alpha_node::{StreamAlphaNode, WindowSpec};
use rust_rule_engine::streaming::window::WindowType;
use std::time::Duration;

let window = WindowSpec {
    duration: Duration::from_secs(60),
    window_type: WindowType::Session {
        timeout: Duration::from_secs(5),  // Gap threshold
    },
};

let mut node = StreamAlphaNode::new("user-events", None, Some(window));
```

**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:**
```grl
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:**
```rust
use rust_rule_engine::rete::{IncrementalEngine, TypedFacts, FactValue};
use rust_rule_engine::rete::grl_loader::GrlReteLoader;

let mut engine = IncrementalEngine::new();
GrlReteLoader::load_from_file("rules.grl", &mut engine)?;

let mut facts = TypedFacts::new();
facts.set("ShoppingCart.items", FactValue::Array(vec![
    FactValue::String("Laptop".to_string())
]));
facts.set("Recommendation.items", FactValue::Array(vec![]));

engine.insert_typed_facts("ShoppingCart", facts.clone());
engine.fire_all(&mut facts, 10);

// Result: Recommendation.items = ["Mouse", "USB-C Hub"] โœ“
```

**Integration with Rule Mining:**

The `+=` operator works seamlessly with [rust-rule-miner](https://github.com/yourusername/rust-rule-miner) for automatic rule generation:

```rust
// Mine association rules from historical data
let rules = miner.mine_association_rules()?;

// Export to GRL with += syntax
let grl = GrlExporter::to_grl(&rules);
// Generates: Recommendation.items += "Phone Case";

// Load and execute in RETE engine
GrlReteLoader::load_from_string(&grl, &mut engine)?;
```

**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]docs/getting-started/
- **[Quick Start]docs/getting-started/QUICK_START.md** - Get up and running in 5 minutes
- **[Installation]docs/getting-started/INSTALLATION.md** - Installation and setup guide
- **[Basic Concepts]docs/getting-started/CONCEPTS.md** - Core concepts explained
- **[First Rules]docs/getting-started/FIRST_RULES.md** - Write your first rules

### ๐ŸŽฏ [Core Features]docs/core-features/
- **[GRL Syntax]docs/core-features/GRL_SYNTAX.md** - Grule Rule Language reference
- **[Features Overview]docs/core-features/FEATURES.md** - All engine capabilities

### โšก [Advanced Features]docs/advanced-features/
- **[RETE Optimization]docs/advanced-features/RETE_OPTIMIZATION.md** - 1,235x join speedup & memory optimizations (v1.13.0+)
- **[RETE Benchmarks]docs/advanced-features/RETE_OPTIMIZATION_BENCHMARKS.md** - Real performance data & analysis (v1.13.0+)
- **[Streaming & CEP]docs/advanced-features/STREAMING.md** - Complex Event Processing
- **[Streaming Architecture]docs/advanced-features/STREAMING_ARCHITECTURE.md** - Deep dive into streaming
- **[Plugins]docs/advanced-features/PLUGINS.md** - Custom plugins and extensions
- **[Performance]docs/advanced-features/PERFORMANCE.md** - Optimization techniques
- **[Redis State]docs/advanced-features/REDIS_STATE_BACKEND.md** - Distributed state management

### ๐Ÿ“– [API Reference]docs/api-reference/
- **[API Reference]docs/api-reference/API_REFERENCE.md** - Complete public API
- **[GRL Query Syntax]docs/api-reference/GRL_QUERY_SYNTAX.md** - Backward chaining queries (v1.11.0+)
- **[Parser Cheat Sheet]docs/api-reference/PARSER_CHEAT_SHEET.md** - Quick syntax reference

### ๐Ÿ“ [Guides]docs/guides/
- **[Backward Chaining Quick Start]docs/BACKWARD_CHAINING_QUICK_START.md** - Goal-driven reasoning
- **[RETE Integration]docs/guides/BACKWARD_CHAINING_RETE_INTEGRATION.md** - Combine forward + backward
- **[Module Management]docs/guides/MODULE_PARSING_GUIDE.md** - Organize rules into modules
- **[Troubleshooting]docs/guides/TROUBLESHOOTING.md** - Common issues and solutions

### ๐Ÿ’ก [Examples]docs/examples/
- **[AI Integration]docs/examples/AI_INTEGRATION.md** - Combine with ML models

**[๐Ÿ“š Full Documentation Index โ†’](docs/README.md)**


---

## ๐Ÿ“œ Older Releases

See [CHANGELOG.md](CHANGELOG.md) for full version history (v0.1.0 - v0.19.0).