rust-rule-engine 1.20.1

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

> **Version:** 1.11.0
> **Prerequisite:** [Quick Start Guide]QUICK_START.md

Understanding the fundamental concepts of the Rust Rule Engine.

---

## 📚 Table of Contents

1. [Facts & Working Memory]#facts--working-memory
2. [Rules]#rules
3. [Pattern Matching]#pattern-matching
4. [Forward vs Backward Chaining]#forward-vs-backward-chaining
5. [RETE Algorithm]#rete-algorithm
6. [GRL Syntax]#grl-syntax

---

## Facts & Working Memory

### What are Facts?

Facts are pieces of data that represent the current state of your system. Think of them as a key-value store:

```rust
use rust_rule_engine::{Facts, Value};

let mut facts = Facts::new();

// Setting facts
facts.set("Customer.Name", Value::String("Alice".to_string()));
facts.set("Customer.Age", Value::Integer(30));
facts.set("Customer.TotalSpent", Value::Number(1500.0));
facts.set("Customer.IsVIP", Value::Boolean(false));
```

### Fact Types

| Type | Rust Value | Example |
|------|------------|---------|
| **String** | `Value::String(String)` | `"Alice"`, `"Premium"` |
| **Integer** | `Value::Integer(i64)` | `42`, `-10`, `1000` |
| **Number** | `Value::Number(f64)` | `3.14`, `99.99`, `1500.0` |
| **Boolean** | `Value::Boolean(bool)` | `true`, `false` |

### Hierarchical Facts

Use dot notation for structured data:

```rust
// Customer facts
facts.set("Customer.Name", Value::String("Alice".to_string()));
facts.set("Customer.Address.City", Value::String("NYC".to_string()));
facts.set("Customer.Address.Zip", Value::String("10001".to_string()));

// Order facts
facts.set("Order.ID", Value::String("ORD-123".to_string()));
facts.set("Order.Total", Value::Number(299.99));
facts.set("Order.Items.Count", Value::Integer(5));
```

### Working Memory

Working memory is the **current state** of all facts. The rule engine:
1. Reads facts from working memory
2. Evaluates rules against these facts
3. Updates working memory with new facts

```rust
let mut facts = Facts::new();          // Empty working memory
facts.set("X", Value::Integer(10));     // Add fact to working memory
engine.run(&mut facts)?;                 // Engine processes working memory
// Facts may be updated by rules
```

---

## Rules

### Rule Structure

A rule has three parts:

```grl
rule "Rule Name" {
    when
        <conditions>     // Pattern to match
    then
        <actions>        // What to do when matched
}
```

### Example Rule

```grl
rule "VIP Discount" {
    when
        Customer.TotalSpent > 1000 &&
        Customer.Membership == "Gold"
    then
        Customer.DiscountRate = 0.2;
        Customer.FreeShipping = true;
        LogMessage("VIP discount applied");
}
```

**Components:**
- **Name**: `"VIP Discount"` - Describes what the rule does
- **When** (Condition): Checks if `TotalSpent > 1000` AND `Membership == "Gold"`
- **Then** (Action): Sets discount rate and enables free shipping

### Rule Execution

Rules are evaluated in the **Recognize-Act Cycle**:

```
1. MATCH: Find all rules whose conditions match current facts
2. SELECT: Choose which rule to fire (conflict resolution)
3. FIRE: Execute the actions of the selected rule
4. REPEAT: Go back to step 1 with updated facts
```

### Rule Syntax

```grl
rule "Name" {
    when
        // Conditions (AND with &&, OR with ||)
        Field1 == "value" &&
        Field2 > 100
    then
        // Actions
        ResultField = "computed value";
        AnotherField = Field2 * 2;
}
```

---

## Pattern Matching

### Simple Patterns

```grl
// Equality
Customer.Type == "VIP"

// Comparison
Order.Total > 100
Product.Stock < 10

// Boolean
Customer.IsActive == true
Item.InStock == false
```

### Complex Patterns

```grl
// Multiple conditions (AND)
Customer.Age > 18 &&
Customer.Income > 50000 &&
Customer.CreditScore > 700

// Disjunction (OR)
(Customer.Type == "VIP" || Customer.TotalSpent > 10000) &&
Customer.IsActive == true

// Negation (NOT)
NOT Customer.IsBanned == true
```

### Arithmetic in Patterns

```grl
// In conditions
Order.Total > Order.SubTotal * 1.1

// In actions
Order.Tax = Order.SubTotal * 0.08;
Order.Final = Order.SubTotal + Order.Tax;
```

---

## Forward vs Backward Chaining

### Forward Chaining (Data-Driven)

**Start with facts → Apply rules → Derive conclusions**

```rust
// Forward chaining example
let mut engine = Engine::new();
engine.add_rule_from_string(r#"
    rule "Infer High Risk" {
        when
            Applicant.CreditScore < 600 &&
            Applicant.Income < 30000
        then
            Applicant.RiskLevel = "high";
    }
"#)?;

let mut facts = Facts::new();
facts.set("Applicant.CreditScore", Value::Integer(550));
facts.set("Applicant.Income", Value::Number(25000.0));

engine.run(&mut facts)?;
// Result: Applicant.RiskLevel = "high" is derived
```

**Use When:**
- You have data and want to find all applicable conclusions
- Real-time event processing
- Business rule automation
- System monitoring and alerts

### Backward Chaining (Goal-Driven)

**Start with goal → Find rules → Request needed facts**

```rust
// Backward chaining example
use rust_rule_engine::backward::BackwardEngine;

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

// Ask: "Is applicant high risk?"
let result = bc_engine.query(
    "Applicant.RiskLevel == \"high\"",
    &mut facts
)?;

if result.provable {
    println!("Applicant is high risk");
}
```

**Use When:**
- You have a question and want to find if it's true
- Diagnostic systems
- Decision support
- Complex queries and reasoning

### Comparison

| Aspect | Forward Chaining | Backward Chaining |
|--------|------------------|-------------------|
| **Direction** | Facts → Conclusions | Goal → Facts |
| **Trigger** | New data arrives | Question asked |
| **Efficiency** | All applicable rules | Only relevant rules |
| **Best For** | Event processing | Queries & diagnosis |
| **Example** | "What can I conclude?" | "Is X true?" |

---

## RETE Algorithm

### What is RETE?

RETE (Latin for "net") is a pattern-matching algorithm that makes forward chaining extremely fast.

**Key Idea:** Don't re-evaluate everything when facts change - only check what's affected.

### How RETE Works

```
1. BUILD NETWORK
   Rules → Compiled into a discrimination network

2. MATCH FACTS
   Facts → Flow through network
   Network → Remembers partial matches

3. UPDATE EFFICIENTLY
   Fact changes → Only affected nodes re-evaluate
   Result: O(1) to O(n) instead of O(rules × facts)
```

### RETE Network Structure

```
         [Root]
           |
    [Type Node: Customer]
           |
    [Alpha Node: Customer.Type == "VIP"]
           |
    [Beta Node: Join with Order]
           |
    [Terminal: Fire Rule]
```

### Performance Benefits

**Without RETE:**
```
10,000 facts × 1,000 rules = 10,000,000 checks
Every fact change: Full re-evaluation
```

**With RETE:**
```
Initial: Build network once
Fact change: Check only affected paths (typically < 100)
Result: 100-1000x faster
```

### Example

```rust
// RETE automatically optimizes this:
engine.add_rule_from_string(r#"
    rule "Complex Pattern" {
        when
            Customer.Type == "VIP" &&
            Order.Total > 1000 &&
            Inventory.Stock > 0
        then
            Process();
    }
"#)?;

// Network built once
// Subsequent fact updates are O(1)
facts.set("Order.Total", Value::Number(1500.0)); // Fast!
```

---

## GRL Syntax

### GRL = Grule Rule Language

A domain-specific language for writing rules in a clear, readable format.

### Basic GRL Structure

```grl
rule "Rule Name" "Optional description" salience 10 {
    when
        <conditions>
    then
        <actions>
}
```

### GRL Features

#### 1. Salience (Priority)

```grl
rule "High Priority" salience 100 {
    when Customer.Type == "VIP"
    then ProcessFirst();
}

rule "Low Priority" salience 10 {
    when Customer.Type == "Regular"
    then ProcessLater();
}
```

Higher salience = Higher priority (fires first)

#### 2. String Functions

```grl
rule "Uppercase Check" {
    when
        Customer.Name.ToUpper() == "ALICE"
    then
        Match = true;
}
```

#### 3. Mathematical Operations

```grl
rule "Calculate Discount" {
    when
        Order.Total > 100
    then
        Order.Discount = Order.Total * 0.1;
        Order.Final = Order.Total - Order.Discount;
}
```

#### 4. Logical Operators

```grl
rule "Complex Logic" {
    when
        (A == 1 || B == 2) &&
        (C > 3 && D < 4) &&
        NOT E == true
    then
        Result = "matched";
}
```

---

## Key Takeaways

✅ **Facts** = Current state (key-value store)
✅ **Rules** = If-then logic (when X then Y)
✅ **Pattern Matching** = Finding facts that match conditions
✅ **Forward Chaining** = Data-driven (facts → conclusions)
✅ **Backward Chaining** = Goal-driven (question → proof)
✅ **RETE** = Fast pattern matching algorithm
✅ **GRL** = Human-readable rule syntax

---

## Next Steps

**📖 Learn More:**
- [Forward Chaining Guide]../core-features/FORWARD_CHAINING.md
- [Backward Chaining Guide]../BACKWARD_CHAINING_QUICK_START.md
- [GRL Syntax Reference]../core-features/GRL_SYNTAX.md

**🔨 Build Something:**
- [First Rules Tutorial]FIRST_RULES.md
- [Real-World Examples]../examples/

**📚 Go Deeper:**
- [API Reference]../api-reference/API_REFERENCE.md
- [Performance Tuning]../advanced-features/PERFORMANCE.md

---

## Navigation

◀️ **Previous: [Quick Start](QUICK_START.md)** | 📚 **[Documentation Home](../README.md)** | ▶️ **Next: [First Rules](FIRST_RULES.md)**