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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
# Backward Chaining Troubleshooting Guide

> **Version**: 1.1.0-beta
> **Last Updated**: 2025-11-27
> **For**: rust-rule-engine backward chaining feature

---

## 📋 Table of Contents

1. [Common Issues]#common-issues
2. [Performance Problems]#performance-problems
3. [Query Errors]#query-errors
4. [Rule Execution Issues]#rule-execution-issues
5. [Memory & Resource Issues]#memory--resource-issues
6. [Integration Problems]#integration-problems
7. [Debugging Tips]#debugging-tips
8. [FAQ]#faq

---

## 🔧 Common Issues

### Issue 1: Feature Flag Not Enabled

**Symptoms**:
```rust
error[E0433]: failed to resolve: could not find `backward` in `rust_rule_engine`
  --> src/main.rs:1:29
   |
1  | use rust_rule_engine::backward::BackwardEngine;
   |                       ^^^^^^^^ could not find `backward` in `rust_rule_engine`
```

**Cause**: The `backward-chaining` feature flag is not enabled.

**Solution**:

Add the feature flag to `Cargo.toml`:

```toml
[dependencies]
rust-rule-engine = { version = "1.1.0-beta", features = ["backward-chaining"] }
```

Or use on command line:
```bash
cargo build --features backward-chaining
cargo test --features backward-chaining
cargo run --features backward-chaining
```

**Verification**:
```bash
cargo tree --features backward-chaining | grep petgraph
# Should show: petgraph v0.6.x
```

---

### Issue 2: Query Returns "Not Provable" When It Should Succeed

**Symptoms**:
```rust
let result = bc_engine.query("User.IsVIP == true", &mut facts)?;
assert!(result.is_provable()); // FAILS
```

**Common Causes**:

#### Cause 2.1: Facts Not Set Correctly

**Problem**: Field name mismatch
```rust
// ❌ Wrong - field name doesn't match query
facts.set("UserIsVIP", Value::Boolean(true));
let result = bc_engine.query("User.IsVIP == true", &mut facts)?;
// Returns: not provable
```

**Solution**: Match field names exactly
```rust
// ✅ Correct - exact match
facts.set("User.IsVIP", Value::Boolean(true));
let result = bc_engine.query("User.IsVIP == true", &mut facts)?;
// Returns: provable
```

#### Cause 2.2: No Rules Conclude the Goal

**Problem**: No rules set the field you're querying
```rust
// Rule sets "Order.Total"
kb.add_rule(Rule::new(
    "CalculateTotal".to_string(),
    conditions,
    vec![ActionType::Set {
        field: "Order.Total".to_string(),
        value: Value::Number(100.0),
    }],
))?;

// ❌ Query different field
let result = bc_engine.query("Order.Amount > 50", &mut facts)?;
// Returns: not provable (no rule sets Order.Amount)
```

**Solution**: Ensure rules conclude what you're querying
```rust
// ✅ Correct - query matches rule conclusion
let result = bc_engine.query("Order.Total > 50", &mut facts)?;
// Returns: provable
```

#### Cause 2.3: Rule Conditions Not Satisfied

**Problem**: Rule exists but its conditions aren't met
```rust
// Rule requires User.Age >= 18
kb.add_rule(Rule::new(
    "CheckAdult".to_string(),
    ConditionGroup::single(Condition::new(
        "User.Age".to_string(),
        Operator::GreaterOrEqual,
        Value::Number(18.0),
    )),
    vec![ActionType::Set {
        field: "User.IsAdult".to_string(),
        value: Value::Boolean(true),
    }],
))?;

// ❌ Age not set
facts.set("User.Name", Value::String("John".to_string()));
let result = bc_engine.query("User.IsAdult == true", &mut facts)?;
// Returns: not provable
```

**Solution**: Set required facts
```rust
// ✅ Correct - all required facts set
facts.set("User.Age", Value::Number(25.0));
let result = bc_engine.query("User.IsAdult == true", &mut facts)?;
// Returns: provable
```

**Debugging**:
```rust
// Enable debug logging
let result = bc_engine.query("User.IsAdult == true", &mut facts)?;

// Check proof trace
if let Some(trace) = result.proof_trace() {
    println!("Proof trace: {:#?}", trace);
    // Shows which rules were tried and why they failed
}

// Check explored goals
println!("Goals explored: {}", result.goals_explored());
```

---

### Issue 3: Query Parsing Errors

**Symptoms**:
```rust
let result = bc_engine.query("User.IsVIP = true", &mut facts);
// Error: Failed to parse query expression
```

**Common Causes**:

#### Cause 3.1: Invalid Operator

**Problem**: Using wrong comparison operator
```rust
// ❌ Wrong - single '=' is not valid
"User.IsVIP = true"

// ❌ Wrong - triple '=' is not valid
"User.Age === 25"
```

**Solution**: Use correct operators
```rust
// ✅ Correct operators
"User.IsVIP == true"   // Equality
"User.Age != 25"       // Not equal
"Score > 50"           // Greater than
"Score < 100"          // Less than
"Points >= 100"        // Greater or equal
"Temperature <= 32"    // Less or equal
```

#### Cause 3.2: Missing Quotes for Strings

**Problem**: String values without quotes
```rust
// ❌ Wrong - string needs quotes
"Status == Active"
```

**Solution**: Quote string literals
```rust
// ✅ Correct
"Status == \"Active\""
```

#### Cause 3.3: Invalid Field Names

**Problem**: Field names with invalid characters
```rust
// ❌ Wrong - spaces in field name
"User Name == \"John\""

// ❌ Wrong - special characters
"User@Email == \"test\""
```

**Solution**: Use valid identifiers
```rust
// ✅ Correct - use dots for nested fields
"User.Name == \"John\""
"User.Email == \"test@example.com\""
```

---

### Issue 4: Performance Degradation

**Symptoms**:
- Queries taking longer than expected
- CPU usage high
- Memory growing over time

**Diagnosis**:
```rust
use std::time::Instant;

let start = Instant::now();
let result = bc_engine.query("Complex.Goal", &mut facts)?;
let elapsed = start.elapsed();

println!("Query time: {:?}", elapsed);
println!("Goals explored: {}", result.goals_explored());

// If elapsed > 100ms for simple queries, investigate
```

**Common Causes & Solutions**: See [Performance Problems](#performance-problems) section.

---

## 🚀 Performance Problems

### Problem 1: Slow Query Execution

**Symptoms**: Queries taking >100ms for <1000 rules

**Diagnosis**:
```rust
let result = bc_engine.query(goal, &mut facts)?;
println!("Goals explored: {}", result.goals_explored());
println!("Rules evaluated: {}", result.rules_evaluated());

// If goals_explored > 1000, you have a deep search tree
```

**Solutions**:

#### Solution 1.1: Verify Conclusion Index is Enabled

```rust
// Check if index is working
use rust_rule_engine::backward::conclusion_index::ConclusionIndex;

let index = bc_engine.conclusion_index(); // If available
let stats = index.stats();
println!("Index stats: {:?}", stats);

// Should show:
// - total_rules > 0
// - indexed_fields > 0
```

If index is empty, rebuild the engine:
```rust
// Force rebuild
let bc_engine = BackwardEngine::new(kb.clone());
```

#### Solution 1.2: Optimize Query Order

Put cheaper conditions first:
```rust
// ❌ Slow - expensive check first
"ExpensiveFunction() && User.IsVIP == true"

// ✅ Fast - cheap check first (short-circuit)
"User.IsVIP == true && ExpensiveFunction()"
```

#### Solution 1.3: Reduce Search Depth

Limit chaining depth if getting too deep:
```rust
let config = BackwardConfig {
    max_depth: 10,  // Limit depth
    ..Default::default()
};

let mut bc_engine = BackwardEngine::with_config(kb, config);
```

#### Solution 1.4: Add Memoization

Reuse engine instance for multiple queries:
```rust
// ❌ Slow - creates new engine each time
for query in queries {
    let bc_engine = BackwardEngine::new(kb.clone());
    bc_engine.query(query, &mut facts)?;
}

// ✅ Fast - reuse engine (memoization works)
let mut bc_engine = BackwardEngine::new(kb.clone());
for query in queries {
    bc_engine.query(query, &mut facts)?;
}
```

---

### Problem 2: High Memory Usage

**Symptoms**: Memory growing continuously, OOM errors

**Diagnosis**:
```rust
// Check proof trace size
let result = bc_engine.query(goal, &mut facts)?;
if let Some(trace) = result.proof_trace() {
    println!("Trace size: {} bytes",
             std::mem::size_of_val(trace));
}
```

**Solutions**:

#### Solution 2.1: Disable Proof Traces for Production

```rust
let config = BackwardConfig {
    generate_proof_trace: false,  // Saves memory
    ..Default::default()
};

let mut bc_engine = BackwardEngine::with_config(kb, config);
```

#### Solution 2.2: Clear Facts After Queries

```rust
for query in queries {
    let mut facts = Facts::new();
    // ... set facts ...
    bc_engine.query(query, &mut facts)?;
    // facts dropped here, memory freed
}
```

#### Solution 2.3: Limit Search Depth

```rust
let config = BackwardConfig {
    max_depth: 20,  // Prevent infinite recursion
    max_goals: 1000,  // Limit goal exploration
    ..Default::default()
};
```

---

### Problem 3: Conclusion Index Not Working

**Symptoms**: Lookups still O(n) slow

**Diagnosis**:
```rust
// Time a lookup
use std::time::Instant;

let start = Instant::now();
let candidates = bc_engine.find_candidates("Field == value");
let elapsed = start.elapsed();

println!("Lookup time: {:?}", elapsed);
// Should be <1µs for O(1) performance
// If >10µs for <1000 rules, index may not be working
```

**Solutions**:

#### Solution 3.1: Check Index Build

```rust
// Verify index was built
let stats = bc_engine.conclusion_index().stats();
assert!(stats.total_rules > 0, "Index not built!");
```

#### Solution 3.2: Rebuild Index After Rule Changes

```rust
// If you modify rules after engine creation:
kb.add_rule(new_rule)?;

// ❌ Index is stale
// bc_engine.query(...) // Uses old index

// ✅ Rebuild engine to recreate index
bc_engine = BackwardEngine::new(kb.clone());
```

---

## ❌ Query Errors

### Error 1: "Field not found in facts"

**Error Message**:
```
Error: Field 'User.IsVIP' not found in facts
```

**Cause**: Querying a field that wasn't set

**Solutions**:

#### Solution 1.1: Set the Fact

```rust
facts.set("User.IsVIP", Value::Boolean(true));
```

#### Solution 1.2: Add Default Values

```rust
// Set defaults for common fields
facts.set("User.IsVIP", Value::Boolean(false));
facts.set("User.IsPremium", Value::Boolean(false));
facts.set("User.Age", Value::Number(0.0));
```

#### Solution 1.3: Use Optional Checks

```rust
// Instead of requiring field to exist:
// ❌ "User.IsVIP == true"

// Use defensive query:
// ✅ "!User.IsBanned"  // Assumes false if not set
```

---

### Error 2: "Circular dependency detected"

**Error Message**:
```
Error: Circular dependency detected in rule chain: Rule1 -> Rule2 -> Rule1
```

**Cause**: Rules create infinite loops

**Example**:
```rust
// Rule1: If B then A
kb.add_rule(Rule::new(
    "Rule1".to_string(),
    ConditionGroup::single(Condition::new("B".to_string(), ...)),
    vec![ActionType::Set { field: "A".to_string(), ... }],
))?;

// Rule2: If A then B (creates cycle!)
kb.add_rule(Rule::new(
    "Rule2".to_string(),
    ConditionGroup::single(Condition::new("A".to_string(), ...)),
    vec![ActionType::Set { field: "B".to_string(), ... }],
))?;
```

**Solutions**:

#### Solution 2.1: Break the Cycle

Redesign rules to avoid circular dependencies:
```rust
// ✅ Correct - linear chain
// Rule1: If C then B
// Rule2: If B then A
// No cycle!
```

#### Solution 2.2: Set Max Depth

```rust
let config = BackwardConfig {
    max_depth: 10,  // Prevent infinite recursion
    ..Default::default()
};
```

---

### Error 3: "Type mismatch in comparison"

**Error Message**:
```
Error: Cannot compare Number(42.0) with String("42")
```

**Cause**: Comparing different types

**Solution**: Ensure types match
```rust
// ❌ Wrong types
facts.set("Age", Value::Number(42.0));
query("Age == \"42\"")  // Comparing number to string

// ✅ Correct - matching types
facts.set("Age", Value::Number(42.0));
query("Age == 42")  // Both numbers
```

---

## 🔄 Rule Execution Issues

### Issue 1: Rules Not Firing

**Symptoms**: Expected rule doesn't execute

**Diagnosis**:
```rust
// Add debug output
let result = bc_engine.query(goal, &mut facts)?;
println!("Rules tried: {:#?}", result.rules_tried());
println!("Rules succeeded: {:#?}", result.rules_succeeded());
```

**Common Causes**:

#### Cause 1.1: Rule Disabled

```rust
// Check if rule is enabled
if let Some(rule) = kb.get_rule("MyRule") {
    println!("Enabled: {}", rule.enabled);
}

// Enable if needed
kb.enable_rule("MyRule")?;
```

#### Cause 1.2: Rule Conditions Not Met

```rust
// Check what conditions failed
let result = bc_engine.query(goal, &mut facts)?;
if let Some(trace) = result.proof_trace() {
    for step in trace.steps() {
        if !step.succeeded() {
            println!("Failed: {} - Reason: {}",
                     step.rule_name(),
                     step.failure_reason());
        }
    }
}
```

#### Cause 1.3: Wrong Condition Operator

```rust
// ❌ Wrong operator
Condition::new("Age".to_string(), Operator::Greater, Value::Number(18.0))
// Requires Age > 18 (not >= 18)

// ✅ Correct operator for "18 or older"
Condition::new("Age".to_string(), Operator::GreaterOrEqual, Value::Number(18.0))
```

---

### Issue 2: Facts Not Derived

**Symptoms**: Rule fires but doesn't set facts

**Diagnosis**:
```rust
println!("Facts before: {:?}", facts.all());
let result = bc_engine.query(goal, &mut facts)?;
println!("Facts after: {:?}", facts.all());
// Check if new facts were added
```

**Cause**: Need to pass mutable reference
```rust
// ❌ Wrong - immutable reference
bc_engine.query(goal, &facts)?;

// ✅ Correct - mutable reference
bc_engine.query(goal, &mut facts)?;
```

---

## 💾 Memory & Resource Issues

### Issue 1: Memory Leak

**Symptoms**: Memory grows without bound

**Diagnosis**:
```rust
use std::mem::size_of_val;

println!("Engine size: {}", size_of_val(&bc_engine));
println!("Facts size: {}", size_of_val(&facts));
```

**Solutions**:

#### Solution 1.1: Drop Unused Engines

```rust
// ❌ Memory leak - engine held in Vec
let mut engines = Vec::new();
for _ in 0..1000 {
    engines.push(BackwardEngine::new(kb.clone()));
}

// ✅ Correct - reuse engine
let mut bc_engine = BackwardEngine::new(kb.clone());
for _ in 0..1000 {
    bc_engine.query(goal, &mut facts)?;
}
```

#### Solution 1.2: Clear Memoization Cache

```rust
// If using custom memoization
bc_engine.clear_cache();
```

---

### Issue 2: Stack Overflow

**Symptoms**:
```
thread 'main' has overflowed its stack
fatal runtime error: stack overflow
```

**Cause**: Deep recursion in rule chain

**Solutions**:

#### Solution 2.1: Limit Depth

```rust
let config = BackwardConfig {
    max_depth: 50,  // Adjust based on needs
    ..Default::default()
};
```

#### Solution 2.2: Increase Stack Size

```rust
// In Cargo.toml
[profile.dev]
opt-level = 0

// Or via environment
RUST_MIN_STACK=8388608 cargo run
```

#### Solution 2.3: Use Iterative Search

```rust
let config = BackwardConfig {
    search_strategy: SearchStrategy::BreadthFirst,  // Less stack usage
    ..Default::default()
};
```

---

## 🔌 Integration Problems

### Issue 1: Thread Safety

**Symptoms**:
```
error[E0277]: `BackwardEngine` cannot be shared between threads safely
```

**Cause**: `BackwardEngine` is not `Send`/`Sync` by default

**Solution**: Use thread-local engines
```rust
use std::thread;

thread::spawn(move || {
    let bc_engine = BackwardEngine::new(kb.clone());
    // Use engine in this thread
});
```

Or use Arc + Mutex:
```rust
use std::sync::{Arc, Mutex};

let bc_engine = Arc::new(Mutex::new(BackwardEngine::new(kb)));

let engine_clone = bc_engine.clone();
thread::spawn(move || {
    let mut engine = engine_clone.lock().unwrap();
    engine.query(goal, &mut facts)?;
});
```

---

### Issue 2: Serialization

**Symptoms**: Cannot serialize `BackwardEngine`

**Cause**: Engine contains function pointers and non-serializable state

**Solution**: Serialize only the knowledge base
```rust
use serde_json;

// ✅ Serialize KB
let json = serde_json::to_string(&kb)?;

// Recreate engine from KB
let kb: KnowledgeBase = serde_json::from_str(&json)?;
let bc_engine = BackwardEngine::new(kb);
```

---

## 🐛 Debugging Tips

### Tip 1: Enable Debug Logging

```rust
// Set environment variable
RUST_LOG=debug cargo run

// Or in code
env_logger::init();
```

### Tip 2: Inspect Proof Traces

```rust
let result = bc_engine.query(goal, &mut facts)?;

if let Some(trace) = result.proof_trace() {
    println!("=== PROOF TRACE ===");
    for (i, step) in trace.steps().iter().enumerate() {
        println!("Step {}: {}", i, step.rule_name());
        println!("  Goal: {}", step.goal());
        println!("  Success: {}", step.succeeded());
        if !step.succeeded() {
            println!("  Reason: {}", step.failure_reason());
        }
    }
}
```

### Tip 3: Benchmark Individual Components

```rust
use std::time::Instant;

// Test expression parsing
let start = Instant::now();
let expr = ExpressionParser::parse(query)?;
println!("Parse time: {:?}", start.elapsed());

// Test index lookup
let start = Instant::now();
let candidates = index.find_candidates(goal);
println!("Lookup time: {:?}", start.elapsed());

// Test evaluation
let start = Instant::now();
let result = expr.evaluate(&facts)?;
println!("Eval time: {:?}", start.elapsed());
```

### Tip 4: Validate Rules

```rust
// Check rule structure
for rule in kb.get_rules() {
    println!("Rule: {}", rule.name);
    println!("  Conditions: {}", rule.conditions.len());
    println!("  Actions: {}", rule.actions.len());
    println!("  Enabled: {}", rule.enabled);

    // Validate has conclusions
    if rule.actions.is_empty() {
        eprintln!("WARNING: Rule {} has no actions!", rule.name);
    }
}
```

### Tip 5: Test with Minimal Examples

Start with simplest possible case:
```rust
// Minimal test
let mut kb = KnowledgeBase::new("test");
kb.add_rule(Rule::new(
    "Simple".to_string(),
    ConditionGroup::single(Condition::new(
        "A".to_string(),
        Operator::Equal,
        Value::Boolean(true),
    )),
    vec![ActionType::Set {
        field: "B".to_string(),
        value: Value::Boolean(true),
    }],
))?;

let mut bc_engine = BackwardEngine::new(kb);
let mut facts = Facts::new();
facts.set("A", Value::Boolean(true));

let result = bc_engine.query("B == true", &mut facts)?;
assert!(result.is_provable());  // Should pass
```

If minimal test fails, problem is in setup, not logic.

---

## ❓ FAQ

### Q1: How many rules can backward chaining handle?

**A**: Tested up to **10,000 rules** with good performance. The Conclusion Index provides O(1) lookup, so performance scales well. However, query complexity matters more than rule count.

**Recommendations**:
- <1000 rules: Excellent performance
- 1000-5000 rules: Good performance
- 5000-10000 rules: Acceptable performance
- \>10000 rules: Consider partitioning or caching

---

### Q2: Should I use forward or backward chaining?

**A**:

**Use Backward Chaining when**:
- ✅ You have a specific goal to prove
- ✅ Large rule set with sparse activation
- ✅ Goal-oriented reasoning needed
- ✅ "What if" queries

**Use Forward Chaining when**:
- ✅ Processing all facts/events
- ✅ Real-time rule execution
- ✅ Dense rule activation
- ✅ Event-driven systems

**Use Both**:
Many systems benefit from hybrid approaches.

---

### Q3: Can I mix forward and backward chaining?

**A**: Yes! Common pattern:
```rust
// Forward chaining for real-time processing
forward_engine.run(&mut facts)?;

// Backward chaining for queries
bc_engine.query("IsEligible == true", &mut facts)?;
```

---

### Q4: How do I debug infinite loops?

**A**:

1. **Set max depth**:
```rust
let config = BackwardConfig {
    max_depth: 10,
    ..Default::default()
};
```

2. **Enable proof trace**:
```rust
let result = bc_engine.query(goal, &mut facts)?;
if let Some(trace) = result.proof_trace() {
    // Check for repeating patterns
    let rule_names: Vec<_> = trace.steps()
        .iter()
        .map(|s| s.rule_name())
        .collect();
    println!("Rule sequence: {:?}", rule_names);
}
```

3. **Check for circular dependencies**:
```rust
// Use dependency analyzer
let deps = kb.analyze_dependencies();
for cycle in deps.cycles() {
    eprintln!("Cycle detected: {:?}", cycle);
}
```

---

### Q5: Why is my query slow despite having the index?

**A**: Common reasons:

1. **Deep chaining**: Goal requires many rule firings
   - Solution: Simplify rule chains or set facts directly

2. **Wide search**: Many candidate rules per goal
   - Solution: Make rule conditions more specific

3. **Complex expressions**: Expensive evaluation
   - Solution: Simplify expressions, move expensive checks last

4. **No memoization**: Recomputing same goals
   - Solution: Reuse engine instance

---

### Q6: How do I handle missing facts gracefully?

**A**:

**Option 1**: Default values
```rust
facts.set_default("User.IsVIP", Value::Boolean(false));
```

**Option 2**: Defensive queries
```rust
// Instead of: "User.IsVIP == true"
// Use: "User.IsVIP == true || User.IsPremium == true"
```

**Option 3**: Optional pattern
```rust
// Check before querying
if facts.has("User.IsVIP") {
    bc_engine.query("User.IsVIP == true", &mut facts)?;
}
```

---

### Q7: Can I use custom functions in expressions?

**A**: Not directly in v1.1.0. Planned for v1.2.0.

**Workaround**: Derive facts first
```rust
// Instead of: "IsEligible(User)"
// Do:
let is_eligible = check_eligibility(&user);
facts.set("User.IsEligible", Value::Boolean(is_eligible));
bc_engine.query("User.IsEligible == true", &mut facts)?;
```

---

## 📞 Getting Help

### Still Stuck?

1. **Check Examples**: See `examples/09-backward-chaining/` for working code

2. **Run Benchmarks**: Compare your performance with benchmarks
   ```bash
   cargo bench --features backward-chaining --bench backward_chaining_benchmarks
   ```

3. **Enable Debug Logs**: Get detailed execution traces
   ```bash
   RUST_LOG=debug cargo run --features backward-chaining
   ```

4. **File an Issue**: https://github.com/KSD-CO/rust-rule-engine/issues
   - Include: Rust version, cargo.toml, minimal reproduction
   - Attach: Debug logs, proof traces, benchmark results

5. **Check Documentation**:
   - [Implementation Plan]../.planning/BACKWARD_CHAINING_IMPLEMENTATION_PLAN.md
   - [Performance Analysis]../.planning/BACKWARD_CHAINING_PERFORMANCE.md
   - [API Docs]https://docs.rs/rust-rule-engine

---

## 🔄 Updates

This guide is updated regularly. Last update: **2025-11-27**

**Changelog**:
- v1.0 (2025-11-27): Initial version for v1.1.0-beta release

---

**Document Version**: 1.0
**For**: rust-rule-engine v1.1.0-beta
**Feedback**: https://github.com/KSD-CO/rust-rule-engine/issues