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
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
497
498
499
500
501
502
503
504
505
506
use rust_rule_engine::engine::facts::Facts;
use rust_rule_engine::engine::knowledge_base::KnowledgeBase;
use rust_rule_engine::engine::{EngineConfig, ParallelConfig, ParallelRuleEngine, RustRuleEngine};
use rust_rule_engine::types::Value;
use std::collections::HashMap;
use std::time::Instant;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("๐Ÿš€ Parallel Rule Engine Demo");
    println!("=============================\n");

    // Demo 1: Performance comparison
    demo_performance_comparison()?;

    // Demo 2: Parallel configuration options
    demo_parallel_configuration()?;

    // Demo 3: Large scale parallel execution
    demo_large_scale_parallel()?;

    println!("\nโœ… Parallel Rule Engine demonstrated successfully!");
    println!("๐ŸŽฏ Key Benefits:");
    println!("   - โšก Faster execution for large rule sets");
    println!("   - ๐Ÿงต Multi-core CPU utilization");
    println!("   - ๐Ÿ”ง Configurable parallelization");
    println!("   - ๐Ÿ“Š Performance monitoring");

    Ok(())
}

fn demo_performance_comparison() -> Result<(), Box<dyn std::error::Error>> {
    println!("๐Ÿ“‹ Demo 1: Performance Comparison");
    println!("----------------------------------");

    // Create test data
    let facts = create_test_facts();
    let kb = create_performance_test_kb()?;

    println!(
        "๐Ÿ”ง Created {} rules for performance testing",
        kb.get_rules().len()
    );

    // Test 1: Sequential execution
    println!("\n๐ŸŒ Sequential Execution:");
    let start = Instant::now();
    let mut sequential_engine = RustRuleEngine::with_config(
        kb.clone(),
        EngineConfig {
            debug_mode: false,
            max_cycles: 1,
            ..Default::default()
        },
    );
    register_test_functions(&mut sequential_engine);
    let sequential_result = sequential_engine.execute(&facts)?;
    let sequential_time = start.elapsed();

    println!("   โฑ๏ธ  Time: {:?}", sequential_time);
    println!("   ๐Ÿ”ฅ Rules fired: {}", sequential_result.rules_fired);

    // Test 2: Parallel execution
    println!("\nโšก Parallel Execution:");
    let start = Instant::now();
    let mut parallel_engine = ParallelRuleEngine::new(ParallelConfig::default());
    register_test_functions_parallel(&mut parallel_engine);
    let parallel_result = parallel_engine.execute_parallel(&kb, &facts, false)?;
    let parallel_time = start.elapsed();

    println!("   โฑ๏ธ  Time: {:?}", parallel_time);
    println!("   {}", parallel_result.get_stats());

    // Performance comparison
    if sequential_time > parallel_time {
        let speedup = sequential_time.as_millis() as f64 / parallel_time.as_millis() as f64;
        println!("\n๐Ÿš€ Parallel execution is {:.2}x faster!", speedup);
    } else {
        println!("\nโš ๏ธ  Sequential was faster (threading overhead for small rule sets)");
    }

    Ok(())
}

fn demo_parallel_configuration() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n๐Ÿ“‹ Demo 2: Parallel Configuration Options");
    println!("------------------------------------------");

    let facts = create_test_facts();
    let kb = create_performance_test_kb()?;

    // Test different configurations
    let configs = vec![
        ("Default", ParallelConfig::default()),
        (
            "High Parallelism",
            ParallelConfig {
                enabled: true,
                max_threads: 8,
                min_rules_per_thread: 1,
                dependency_analysis: true,
            },
        ),
        (
            "Conservative",
            ParallelConfig {
                enabled: true,
                max_threads: 2,
                min_rules_per_thread: 5,
                dependency_analysis: true,
            },
        ),
        (
            "Disabled",
            ParallelConfig {
                enabled: false,
                ..Default::default()
            },
        ),
    ];

    for (name, config) in configs {
        println!("\n๐Ÿ”ง Testing {} configuration:", name);
        println!("   Max threads: {}", config.max_threads);
        println!("   Min rules per thread: {}", config.min_rules_per_thread);
        println!("   Enabled: {}", config.enabled);

        let start = Instant::now();
        let mut engine = ParallelRuleEngine::new(config);
        register_test_functions_parallel(&mut engine);
        let result = engine.execute_parallel(&kb, &facts, false)?;
        let execution_time = start.elapsed();

        println!("   โฑ๏ธ  Execution time: {:?}", execution_time);
        println!("   ๐Ÿ”ฅ Rules fired: {}", result.total_rules_fired);
        println!("   ๐Ÿ“ˆ Speedup: {:.2}x", result.parallel_speedup);
    }

    Ok(())
}

fn demo_large_scale_parallel() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n๐Ÿ“‹ Demo 3: Large Scale Parallel Execution");
    println!("------------------------------------------");

    // Create a large knowledge base
    let kb = create_large_scale_kb(50)?; // 50 rules
    let facts = create_test_facts();

    println!(
        "๐Ÿ—๏ธ  Created knowledge base with {} rules",
        kb.get_rules().len()
    );

    // Test with different thread counts
    let thread_counts = vec![1, 2, 4, 8];

    for thread_count in thread_counts {
        println!("\n๐Ÿงต Testing with {} threads:", thread_count);

        let config = ParallelConfig {
            enabled: true,
            max_threads: thread_count,
            min_rules_per_thread: 1,
            dependency_analysis: true,
        };

        let start = Instant::now();
        let mut engine = ParallelRuleEngine::new(config);
        register_test_functions_parallel(&mut engine);
        let result = engine.execute_parallel(&kb, &facts, false)?;
        let execution_time = start.elapsed();

        println!("   โฑ๏ธ  Time: {:?}", execution_time);
        println!("   ๐Ÿ”ฅ Rules fired: {}", result.total_rules_fired);
        println!("   ๐Ÿ“ˆ Theoretical speedup: {:.2}x", result.parallel_speedup);
        println!(
            "   ๐Ÿ“Š Rules per second: {:.0}",
            result.total_rules_evaluated as f64 / execution_time.as_secs_f64()
        );
    }

    Ok(())
}

fn create_test_facts() -> Facts {
    let facts = Facts::new();
    facts.set("User", {
        let mut user = HashMap::new();
        user.insert("Age".to_string(), Value::Number(25.0));
        user.insert("Country".to_string(), Value::String("US".to_string()));
        user.insert("SpendingTotal".to_string(), Value::Number(1500.0));
        user.insert("IsVIP".to_string(), Value::Boolean(false));
        user.insert(
            "Category".to_string(),
            Value::String("standard".to_string()),
        );
        Value::Object(user)
    });

    facts.set("Order", {
        let mut order = HashMap::new();
        order.insert("Amount".to_string(), Value::Number(100.0));
        order.insert(
            "Category".to_string(),
            Value::String("electronics".to_string()),
        );
        order.insert("ItemCount".to_string(), Value::Number(3.0));
        Value::Object(order)
    });

    facts
}

fn create_performance_test_kb() -> Result<KnowledgeBase, Box<dyn std::error::Error>> {
    let kb = KnowledgeBase::new("PerformanceTestKB");

    let rules = vec![
        r#"rule "AgeValidation" salience 10 {
            when User.Age >= 18
            then validateAge("adult");
        }"#,
        r#"rule "CountryCheck" salience 10 {
            when User.Country == "US"
            then processCountry("US processing");
        }"#,
        r#"rule "SpendingAnalysis" salience 10 {
            when User.SpendingTotal > 1000.0
            then analyzeSpending("high spender");
        }"#,
        r#"rule "VIPCheck" salience 9 {
            when User.IsVIP == false
            then checkVIPStatus("standard user");
        }"#,
        r#"rule "CategoryProcessing" salience 9 {
            when User.Category == "standard"
            then processCategory("standard processing");
        }"#,
        r#"rule "OrderValidation" salience 8 {
            when Order.Amount > 50.0
            then validateOrder("order valid");
        }"#,
        r#"rule "ItemCountCheck" salience 8 {
            when Order.ItemCount >= 2.0
            then checkItemCount("multiple items");
        }"#,
        r#"rule "ElectronicsRule" salience 7 {
            when Order.Category == "electronics"
            then processElectronics("electronics order");
        }"#,
    ];

    for rule_str in rules {
        kb.add_rules_from_grl(rule_str)?;
    }

    Ok(kb)
}

fn create_large_scale_kb(rule_count: usize) -> Result<KnowledgeBase, Box<dyn std::error::Error>> {
    let kb = KnowledgeBase::new("LargeScaleKB");

    for i in 0..rule_count {
        let salience = 10 - (i % 10) as i32; // Vary salience from 1-10
        let rule_str = format!(
            r#"rule "Rule{}" salience {} {{
                when User.Age >= {}
                then processRule("Rule {} executed");
            }}"#,
            i,
            salience,
            i % 30 + 18,
            i
        );
        kb.add_rules_from_grl(&rule_str)?;
    }

    Ok(kb)
}

fn register_test_functions(engine: &mut RustRuleEngine) {
    engine.register_function("validateAge", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     โœ… Age validation: {}", msg);
        }
        Ok(Value::Null)
    });

    // Also register as an action handler in case the GRL emits a Custom action
    engine.register_action_handler(
        "validateAge",
        |params: &std::collections::HashMap<String, Value>, _facts: &Facts| {
            if let Some(v) = params.get("0") {
                match v {
                    Value::String(msg) => println!("     โœ… Age validation (action): {}", msg),
                    _ => println!(
                        "     โœ… Age validation (action) with non-string param: {:?}",
                        v
                    ),
                }
            }
            Ok(())
        },
    );

    // Register other action handlers used by the performance KB rules
    engine.register_action_handler(
        "processCountry",
        |params: &std::collections::HashMap<String, Value>, _facts: &Facts| {
            if let Some(Value::String(msg)) = params.get("0") {
                println!("     ๐ŸŒŽ Country processing (action): {}", msg);
            }
            Ok(())
        },
    );

    engine.register_action_handler(
        "analyzeSpending",
        |params: &std::collections::HashMap<String, Value>, _facts: &Facts| {
            if let Some(Value::String(msg)) = params.get("0") {
                println!("     ๐Ÿ’ฐ Spending analysis (action): {}", msg);
            }
            Ok(())
        },
    );

    engine.register_action_handler(
        "checkVIPStatus",
        |params: &std::collections::HashMap<String, Value>, _facts: &Facts| {
            if let Some(Value::String(msg)) = params.get("0") {
                println!("     โญ VIP check (action): {}", msg);
            }
            Ok(())
        },
    );

    engine.register_action_handler(
        "processCategory",
        |params: &std::collections::HashMap<String, Value>, _facts: &Facts| {
            if let Some(Value::String(msg)) = params.get("0") {
                println!("     ๐Ÿ“‚ Category processing (action): {}", msg);
            }
            Ok(())
        },
    );

    engine.register_action_handler(
        "validateOrder",
        |params: &std::collections::HashMap<String, Value>, _facts: &Facts| {
            if let Some(Value::String(msg)) = params.get("0") {
                println!("     ๐Ÿ›’ Order validation (action): {}", msg);
            }
            Ok(())
        },
    );

    engine.register_action_handler(
        "checkItemCount",
        |params: &std::collections::HashMap<String, Value>, _facts: &Facts| {
            if let Some(Value::String(msg)) = params.get("0") {
                println!("     ๐Ÿ“ฆ Item count check (action): {}", msg);
            }
            Ok(())
        },
    );

    engine.register_action_handler(
        "processElectronics",
        |params: &std::collections::HashMap<String, Value>, _facts: &Facts| {
            if let Some(Value::String(msg)) = params.get("0") {
                println!("     โšก Electronics processing (action): {}", msg);
            }
            Ok(())
        },
    );

    engine.register_action_handler(
        "processRule",
        |params: &std::collections::HashMap<String, Value>, _facts: &Facts| {
            if let Some(Value::String(msg)) = params.get("0") {
                println!("     ๐Ÿ”ง {}", msg);
            }
            Ok(())
        },
    );

    engine.register_function("processCountry", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     ๐ŸŒŽ Country processing: {}", msg);
        }
        Ok(Value::Null)
    });

    engine.register_function("analyzeSpending", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     ๐Ÿ’ฐ Spending analysis: {}", msg);
        }
        Ok(Value::Null)
    });

    engine.register_function("checkVIPStatus", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     โญ VIP check: {}", msg);
        }
        Ok(Value::Null)
    });

    engine.register_function("processCategory", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     ๐Ÿ“‚ Category processing: {}", msg);
        }
        Ok(Value::Null)
    });

    engine.register_function("validateOrder", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     ๐Ÿ›’ Order validation: {}", msg);
        }
        Ok(Value::Null)
    });

    engine.register_function("checkItemCount", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     ๐Ÿ“ฆ Item count check: {}", msg);
        }
        Ok(Value::Null)
    });

    engine.register_function("processElectronics", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     โšก Electronics processing: {}", msg);
        }
        Ok(Value::Null)
    });

    engine.register_function("processRule", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     ๐Ÿ”ง {}", msg);
        }
        Ok(Value::Null)
    });
}

fn register_test_functions_parallel(engine: &mut ParallelRuleEngine) {
    engine.register_function("validateAge", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     โœ… Age validation: {}", msg);
        }
        Ok(Value::Null)
    });

    engine.register_function("processCountry", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     ๐ŸŒŽ Country processing: {}", msg);
        }
        Ok(Value::Null)
    });

    engine.register_function("analyzeSpending", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     ๐Ÿ’ฐ Spending analysis: {}", msg);
        }
        Ok(Value::Null)
    });

    engine.register_function("checkVIPStatus", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     โญ VIP check: {}", msg);
        }
        Ok(Value::Null)
    });

    engine.register_function("processCategory", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     ๐Ÿ“‚ Category processing: {}", msg);
        }
        Ok(Value::Null)
    });

    engine.register_function("validateOrder", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     ๐Ÿ›’ Order validation: {}", msg);
        }
        Ok(Value::Null)
    });

    engine.register_function("checkItemCount", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     ๐Ÿ“ฆ Item count check: {}", msg);
        }
        Ok(Value::Null)
    });

    engine.register_function("processElectronics", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     โšก Electronics processing: {}", msg);
        }
        Ok(Value::Null)
    });

    engine.register_function("processRule", |args: &[Value], _facts| {
        if let Some(Value::String(msg)) = args.first() {
            println!("     ๐Ÿ”ง {}", msg);
        }
        Ok(Value::Null)
    });
}