1use crate::{Rule, RuleAtom, RuleEngine, Term};
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10use std::sync::{Arc, Mutex};
11use std::thread;
12use std::time::{Duration, Instant};
13use tracing::{debug, info, warn};
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct PerformanceMetrics {
18 pub total_time: Duration,
20 pub rule_loading_time: Duration,
22 pub fact_processing_time: Duration,
24 pub forward_chaining_time: Duration,
26 pub backward_chaining_time: Duration,
28 pub rules_processed: usize,
30 pub facts_processed: usize,
32 pub inferred_facts: usize,
34 pub memory_stats: MemoryStats,
36 pub rule_timings: HashMap<String, Duration>,
38 pub warnings: Vec<String>,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct MemoryStats {
45 pub peak_memory_usage: usize,
47 pub facts_memory: usize,
49 pub rules_memory: usize,
51 pub derived_facts_memory: usize,
53}
54
55#[derive(Debug)]
57pub struct RuleEngineProfiler {
58 start_time: Instant,
60 operation_timings: HashMap<String, Vec<Duration>>,
62 operation_stack: Vec<(String, Instant)>,
64 memory_snapshots: Vec<(String, usize)>,
66 thresholds: PerformanceThresholds,
68}
69
70#[derive(Debug, Clone)]
72pub struct PerformanceThresholds {
73 pub max_rule_loading_time: u64,
75 pub max_forward_chaining_time: u64,
77 pub max_backward_chaining_time: u64,
79 pub max_memory_usage: usize,
81 pub max_iterations: usize,
83}
84
85impl Default for PerformanceThresholds {
86 fn default() -> Self {
87 Self {
88 max_rule_loading_time: 1000, max_forward_chaining_time: 5000, max_backward_chaining_time: 2000, max_memory_usage: 1024, max_iterations: 1000,
93 }
94 }
95}
96
97impl Default for RuleEngineProfiler {
98 fn default() -> Self {
99 Self::new()
100 }
101}
102
103impl RuleEngineProfiler {
104 pub fn new() -> Self {
106 Self {
107 start_time: Instant::now(),
108 operation_timings: HashMap::new(),
109 operation_stack: Vec::new(),
110 memory_snapshots: Vec::new(),
111 thresholds: PerformanceThresholds::default(),
112 }
113 }
114
115 pub fn with_thresholds(thresholds: PerformanceThresholds) -> Self {
117 Self {
118 start_time: Instant::now(),
119 operation_timings: HashMap::new(),
120 operation_stack: Vec::new(),
121 memory_snapshots: Vec::new(),
122 thresholds,
123 }
124 }
125
126 pub fn start_operation(&mut self, operation_name: &str) {
128 debug!("Starting operation: {operation_name}");
129 self.operation_stack
130 .push((operation_name.to_string(), Instant::now()));
131 }
132
133 pub fn end_operation(&mut self, operation_name: &str) {
135 if let Some((name, start_time)) = self.operation_stack.pop() {
136 if name == operation_name {
137 let duration = start_time.elapsed();
138 debug!("Completed operation '{operation_name}' in {duration:?}");
139
140 self.operation_timings
141 .entry(operation_name.to_string())
142 .or_default()
143 .push(duration);
144 } else {
145 warn!("Operation stack mismatch: expected '{name}', got '{operation_name}'");
146 }
147 } else {
148 warn!("No operation to end for '{operation_name}'");
149 }
150 }
151
152 pub fn record_memory_snapshot(&mut self, label: &str) {
154 let estimated_memory = self.estimate_memory_usage();
157 self.memory_snapshots
158 .push((label.to_string(), estimated_memory));
159 debug!("Memory snapshot '{label}': {estimated_memory} bytes");
160 }
161
162 fn estimate_memory_usage(&self) -> usize {
164 let base_size = std::mem::size_of::<RuleEngine>();
167 let timing_size = self.operation_timings.len() * 64; let snapshot_size = self.memory_snapshots.len() * 32;
169
170 base_size + timing_size + snapshot_size
171 }
172
173 pub fn profile_operation<F, R>(&mut self, operation_name: &str, operation: F) -> R
175 where
176 F: FnOnce() -> R,
177 {
178 self.start_operation(operation_name);
179 self.record_memory_snapshot(&format!("before_{operation_name}"));
180
181 let result = operation();
182
183 self.record_memory_snapshot(&format!("after_{operation_name}"));
184 self.end_operation(operation_name);
185
186 result
187 }
188
189 pub fn generate_report(&self) -> PerformanceMetrics {
191 let total_time = self.start_time.elapsed();
192 let mut warnings = Vec::new();
193
194 let rule_loading_time = self.get_total_time("rule_loading");
196 let fact_processing_time = self.get_total_time("fact_processing");
197 let forward_chaining_time = self.get_total_time("forward_chaining");
198 let backward_chaining_time = self.get_total_time("backward_chaining");
199
200 if rule_loading_time.as_millis() > self.thresholds.max_rule_loading_time as u128 {
202 warnings.push(format!(
203 "Rule loading time ({rule_loading_time:?}) exceeds threshold ({}ms)",
204 self.thresholds.max_rule_loading_time
205 ));
206 }
207
208 if forward_chaining_time.as_millis() > self.thresholds.max_forward_chaining_time as u128 {
209 warnings.push(format!(
210 "Forward chaining time ({forward_chaining_time:?}) exceeds threshold ({}ms)",
211 self.thresholds.max_forward_chaining_time
212 ));
213 }
214
215 if backward_chaining_time.as_millis() > self.thresholds.max_backward_chaining_time as u128 {
216 warnings.push(format!(
217 "Backward chaining time ({backward_chaining_time:?}) exceeds threshold ({}ms)",
218 self.thresholds.max_backward_chaining_time
219 ));
220 }
221
222 let peak_memory = self
224 .memory_snapshots
225 .iter()
226 .map(|(_, size)| *size)
227 .max()
228 .unwrap_or(0);
229
230 if peak_memory > self.thresholds.max_memory_usage * 1024 * 1024 {
231 warnings.push(format!(
232 "Peak memory usage ({peak_memory} bytes) exceeds threshold ({} MB)",
233 self.thresholds.max_memory_usage
234 ));
235 }
236
237 let mut rule_timings = HashMap::new();
239 for (operation, durations) in &self.operation_timings {
240 let total: Duration = durations.iter().sum();
241 rule_timings.insert(operation.clone(), total);
242 }
243
244 PerformanceMetrics {
245 total_time,
246 rule_loading_time,
247 fact_processing_time,
248 forward_chaining_time,
249 backward_chaining_time,
250 rules_processed: self.get_operation_count("rule_loading"),
251 facts_processed: self.get_operation_count("fact_processing"),
252 inferred_facts: self.get_operation_count("fact_inference"),
253 memory_stats: MemoryStats {
254 peak_memory_usage: peak_memory,
255 facts_memory: peak_memory / 3, rules_memory: peak_memory / 3,
257 derived_facts_memory: peak_memory / 3,
258 },
259 rule_timings,
260 warnings,
261 }
262 }
263
264 fn get_total_time(&self, operation: &str) -> Duration {
266 self.operation_timings
267 .get(operation)
268 .map(|durations| durations.iter().sum())
269 .unwrap_or(Duration::ZERO)
270 }
271
272 fn get_operation_count(&self, operation: &str) -> usize {
274 self.operation_timings
275 .get(operation)
276 .map(|durations| durations.len())
277 .unwrap_or(0)
278 }
279
280 pub fn print_report(&self) {
282 let metrics = self.generate_report();
283
284 println!("=== Rule Engine Performance Report ===");
285 println!("Total execution time: {:?}", metrics.total_time);
286 println!("Rule loading time: {:?}", metrics.rule_loading_time);
287 println!("Fact processing time: {:?}", metrics.fact_processing_time);
288 println!("Forward chaining time: {:?}", metrics.forward_chaining_time);
289 println!(
290 "Backward chaining time: {:?}",
291 metrics.backward_chaining_time
292 );
293 println!("Rules processed: {}", metrics.rules_processed);
294 println!("Facts processed: {}", metrics.facts_processed);
295 println!("Inferred facts: {}", metrics.inferred_facts);
296 println!(
297 "Peak memory usage: {} bytes",
298 metrics.memory_stats.peak_memory_usage
299 );
300
301 if !metrics.warnings.is_empty() {
302 println!("\n=== Performance Warnings ===");
303 for warning in &metrics.warnings {
304 println!("⚠️ {warning}");
305 }
306 }
307
308 if !metrics.rule_timings.is_empty() {
309 println!("\n=== Operation Timings ===");
310 let mut sorted_timings: Vec<_> = metrics.rule_timings.iter().collect();
311 sorted_timings.sort_by_key(|(_, duration)| *duration);
312 sorted_timings.reverse();
313
314 for (operation, duration) in sorted_timings {
315 println!("{operation}: {duration:?}");
316 }
317 }
318 }
319
320 pub fn export_json(&self) -> Result<String, serde_json::Error> {
322 let metrics = self.generate_report();
323 serde_json::to_string_pretty(&metrics)
324 }
325}
326
327pub struct PerformanceTestHarness {
329 profiler: RuleEngineProfiler,
330}
331
332impl PerformanceTestHarness {
333 pub fn new() -> Self {
335 Self {
336 profiler: RuleEngineProfiler::new(),
337 }
338 }
339
340 pub fn run_comprehensive_test(
342 &mut self,
343 rules: Vec<Rule>,
344 facts: Vec<RuleAtom>,
345 ) -> PerformanceMetrics {
346 info!(
347 "Starting comprehensive performance test with {rule_count} rules and {fact_count} facts",
348 rule_count = rules.len(),
349 fact_count = facts.len()
350 );
351
352 let mut engine = RuleEngine::new();
353
354 self.profiler.profile_operation("rule_loading", || {
356 for rule in rules {
357 engine.add_rule(rule);
358 }
359 });
360
361 self.profiler.profile_operation("fact_processing", || {
363 engine.add_facts(facts.clone());
364 });
365
366 let derived_facts = self.profiler.profile_operation("forward_chaining", || {
368 engine.forward_chain(&facts).unwrap_or_default()
369 });
370
371 info!(
372 "Forward chaining derived {derived_fact_count} facts",
373 derived_fact_count = derived_facts.len()
374 );
375
376 if let Some(goal) = facts.first() {
378 self.profiler.profile_operation("backward_chaining", || {
379 engine.backward_chain(goal).unwrap_or(false)
380 });
381 }
382
383 let metrics = self.profiler.generate_report();
384 info!(
385 "Performance test completed in {total_time:?}",
386 total_time = metrics.total_time
387 );
388
389 metrics
390 }
391
392 pub fn run_memory_stress_test(&mut self, scale_factor: usize) -> PerformanceMetrics {
394 info!("Starting memory stress test with scale factor {scale_factor}");
395
396 let mut engine = RuleEngine::new();
397
398 let facts = self.generate_large_fact_set(scale_factor * 1000);
400 let rules = self.generate_large_rule_set(scale_factor * 100);
401
402 self.profiler.record_memory_snapshot("initial");
403
404 self.profiler.profile_operation("bulk_rule_loading", || {
406 for rule in rules {
407 engine.add_rule(rule);
408 }
409 });
410
411 self.profiler.record_memory_snapshot("after_rules");
412
413 self.profiler.profile_operation("bulk_fact_loading", || {
415 engine.add_facts(facts.clone());
416 });
417
418 self.profiler.record_memory_snapshot("after_facts");
419
420 self.profiler
422 .profile_operation("memory_stress_reasoning", || {
423 engine.forward_chain(&facts).unwrap_or_default()
424 });
425
426 self.profiler.record_memory_snapshot("after_reasoning");
427
428 self.profiler.generate_report()
429 }
430
431 fn generate_large_fact_set(&self, size: usize) -> Vec<RuleAtom> {
433 let mut facts = Vec::with_capacity(size);
434
435 for i in 0..size {
436 facts.push(RuleAtom::Triple {
437 subject: Term::Constant(format!("http://example.org/entity{i}")),
438 predicate: Term::Constant(
439 "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),
440 ),
441 object: Term::Constant(format!("http://example.org/Type{}", i % 100)),
442 });
443 }
444
445 facts
446 }
447
448 fn generate_large_rule_set(&self, size: usize) -> Vec<Rule> {
450 let mut rules = Vec::with_capacity(size);
451
452 for i in 0..size {
453 rules.push(Rule {
454 name: format!("large_rule_{i}"),
455 body: vec![RuleAtom::Triple {
456 subject: Term::Variable("X".to_string()),
457 predicate: Term::Constant(
458 "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),
459 ),
460 object: Term::Constant(format!("http://example.org/Type{}", i % 100)),
461 }],
462 head: vec![RuleAtom::Triple {
463 subject: Term::Variable("X".to_string()),
464 predicate: Term::Constant(
465 "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),
466 ),
467 object: Term::Constant(format!("http://example.org/DerivedType{i}")),
468 }],
469 });
470 }
471
472 rules
473 }
474}
475
476impl Default for PerformanceTestHarness {
477 fn default() -> Self {
478 Self::new()
479 }
480}
481
482#[cfg(test)]
483mod tests {
484 use super::*;
485
486 #[test]
487 fn test_profiler_basic_operations() {
488 let mut profiler = RuleEngineProfiler::new();
489
490 profiler.start_operation("test_op");
491 std::thread::sleep(Duration::from_millis(10));
492 profiler.end_operation("test_op");
493
494 let metrics = profiler.generate_report();
495 assert!(metrics.total_time >= Duration::from_millis(10));
496 }
497
498 #[test]
499 fn test_performance_harness() {
500 let mut harness = PerformanceTestHarness::new();
501
502 let rules = vec![Rule {
503 name: "test_rule".to_string(),
504 body: vec![RuleAtom::Triple {
505 subject: Term::Variable("X".to_string()),
506 predicate: Term::Constant("test".to_string()),
507 object: Term::Constant("value".to_string()),
508 }],
509 head: vec![RuleAtom::Triple {
510 subject: Term::Variable("X".to_string()),
511 predicate: Term::Constant("derived".to_string()),
512 object: Term::Constant("result".to_string()),
513 }],
514 }];
515
516 let facts = vec![RuleAtom::Triple {
517 subject: Term::Constant("subject1".to_string()),
518 predicate: Term::Constant("test".to_string()),
519 object: Term::Constant("value".to_string()),
520 }];
521
522 let metrics = harness.run_comprehensive_test(rules, facts);
523 assert!(metrics.rules_processed > 0);
524 }
525
526 #[test]
527 fn test_incremental_reasoning() -> Result<(), Box<dyn std::error::Error>> {
528 let mut engine = IncrementalReasoningEngine::new();
529
530 let rule = Rule {
532 name: "person_human".to_string(),
533 body: vec![RuleAtom::Triple {
534 subject: Term::Variable("X".to_string()),
535 predicate: Term::Constant("type".to_string()),
536 object: Term::Constant("Person".to_string()),
537 }],
538 head: vec![RuleAtom::Triple {
539 subject: Term::Variable("X".to_string()),
540 predicate: Term::Constant("type".to_string()),
541 object: Term::Constant("Human".to_string()),
542 }],
543 };
544
545 engine.add_rules(vec![rule])?;
546
547 let initial_facts = vec![RuleAtom::Triple {
549 subject: Term::Constant("alice".to_string()),
550 predicate: Term::Constant("type".to_string()),
551 object: Term::Constant("Person".to_string()),
552 }];
553
554 let full_results = engine.full_reasoning_with_cache(initial_facts)?;
556 assert!(!full_results.is_empty());
557
558 let new_facts = vec![RuleAtom::Triple {
560 subject: Term::Constant("bob".to_string()),
561 predicate: Term::Constant("type".to_string()),
562 object: Term::Constant("Person".to_string()),
563 }];
564
565 let incremental_results = engine.add_facts_incremental(new_facts)?;
566 assert!(!incremental_results.is_empty());
567
568 let metrics = engine.get_incremental_metrics();
570 assert_eq!(metrics.incremental_updates, 1);
571 Ok(())
572 }
573
574 #[test]
575 fn test_hybrid_reasoning_engine() -> Result<(), Box<dyn std::error::Error>> {
576 let mut engine = HybridReasoningEngine::new(ReasoningStrategy::Adaptive {
577 parallel_threshold: 5,
578 complexity_threshold: 10,
579 });
580
581 let rule = Rule {
583 name: "test_hybrid".to_string(),
584 body: vec![RuleAtom::Triple {
585 subject: Term::Variable("X".to_string()),
586 predicate: Term::Constant("input".to_string()),
587 object: Term::Constant("value".to_string()),
588 }],
589 head: vec![RuleAtom::Triple {
590 subject: Term::Variable("X".to_string()),
591 predicate: Term::Constant("output".to_string()),
592 object: Term::Constant("result".to_string()),
593 }],
594 };
595
596 engine.add_rules(vec![rule])?;
597
598 let small_facts = vec![RuleAtom::Triple {
600 subject: Term::Constant("item1".to_string()),
601 predicate: Term::Constant("input".to_string()),
602 object: Term::Constant("value".to_string()),
603 }];
604
605 let results = engine.reason(small_facts)?;
606 assert!(!results.is_empty());
607
608 let large_facts: Vec<RuleAtom> = (0..10)
610 .map(|i| RuleAtom::Triple {
611 subject: Term::Constant(format!("item{i}")),
612 predicate: Term::Constant("input".to_string()),
613 object: Term::Constant("value".to_string()),
614 })
615 .collect();
616
617 let large_results = engine.reason(large_facts)?;
618 assert!(!large_results.is_empty());
619
620 let metrics = engine.get_performance_metrics();
622 assert!(metrics.total_time > Duration::new(0, 0));
623 Ok(())
624 }
625
626 #[test]
627 fn test_incremental_vs_full_benchmark() -> Result<(), Box<dyn std::error::Error>> {
628 let mut engine = IncrementalReasoningEngine::new();
629
630 let rules = vec![Rule {
632 name: "rule1".to_string(),
633 body: vec![RuleAtom::Triple {
634 subject: Term::Variable("X".to_string()),
635 predicate: Term::Constant("likes".to_string()),
636 object: Term::Constant("food".to_string()),
637 }],
638 head: vec![RuleAtom::Triple {
639 subject: Term::Variable("X".to_string()),
640 predicate: Term::Constant("type".to_string()),
641 object: Term::Constant("FoodLover".to_string()),
642 }],
643 }];
644
645 engine.add_rules(rules)?;
646
647 let initial_facts = vec![RuleAtom::Triple {
649 subject: Term::Constant("alice".to_string()),
650 predicate: Term::Constant("likes".to_string()),
651 object: Term::Constant("food".to_string()),
652 }];
653
654 let new_facts = vec![RuleAtom::Triple {
656 subject: Term::Constant("bob".to_string()),
657 predicate: Term::Constant("likes".to_string()),
658 object: Term::Constant("food".to_string()),
659 }];
660
661 let benchmark = engine.benchmark_incremental_vs_full(initial_facts, new_facts)?;
663
664 assert!(benchmark.full_reasoning_time > Duration::new(0, 0));
666 assert!(benchmark.facts_derived > 0);
667
668 println!("Benchmark results: {benchmark}");
669 Ok(())
670 }
671
672 #[test]
673 fn test_change_tracking() -> Result<(), Box<dyn std::error::Error>> {
674 let mut engine = IncrementalReasoningEngine::new();
675
676 let rule = Rule {
678 name: "change_test".to_string(),
679 body: vec![RuleAtom::Triple {
680 subject: Term::Variable("X".to_string()),
681 predicate: Term::Constant("input".to_string()),
682 object: Term::Variable("Y".to_string()),
683 }],
684 head: vec![RuleAtom::Triple {
685 subject: Term::Variable("X".to_string()),
686 predicate: Term::Constant("output".to_string()),
687 object: Term::Variable("Y".to_string()),
688 }],
689 };
690
691 engine.add_rules(vec![rule])?;
692
693 let facts = vec![RuleAtom::Triple {
695 subject: Term::Constant("test".to_string()),
696 predicate: Term::Constant("input".to_string()),
697 object: Term::Constant("data".to_string()),
698 }];
699
700 let results = engine.add_facts_incremental(facts)?;
701 assert!(!results.is_empty());
702
703 let metrics = engine.get_incremental_metrics();
705 assert_eq!(metrics.incremental_updates, 1);
706 Ok(())
707 }
708}
709
710pub struct ParallelRuleEngine {
712 num_threads: usize,
714 rules: Arc<Mutex<Vec<Rule>>>,
716 facts: Arc<Mutex<Vec<RuleAtom>>>,
718 metrics: Arc<Mutex<PerformanceMetrics>>,
720}
721
722impl ParallelRuleEngine {
723 pub fn new(num_threads: Option<usize>) -> Self {
725 let num_threads = num_threads.unwrap_or_else(|| {
726 std::thread::available_parallelism()
727 .map(|n| n.get())
728 .unwrap_or(4)
729 });
730
731 info!(
732 "Initializing parallel rule engine with {} threads",
733 num_threads
734 );
735
736 Self {
737 num_threads,
738 rules: Arc::new(Mutex::new(Vec::new())),
739 facts: Arc::new(Mutex::new(Vec::new())),
740 metrics: Arc::new(Mutex::new(PerformanceMetrics {
741 total_time: Duration::new(0, 0),
742 rule_loading_time: Duration::new(0, 0),
743 fact_processing_time: Duration::new(0, 0),
744 forward_chaining_time: Duration::new(0, 0),
745 backward_chaining_time: Duration::new(0, 0),
746 rules_processed: 0,
747 facts_processed: 0,
748 inferred_facts: 0,
749 memory_stats: MemoryStats {
750 peak_memory_usage: 0,
751 facts_memory: 0,
752 rules_memory: 0,
753 derived_facts_memory: 0,
754 },
755 rule_timings: HashMap::new(),
756 warnings: Vec::new(),
757 })),
758 }
759 }
760
761 pub fn add_rules(&mut self, rules: Vec<Rule>) -> Result<(), String> {
763 let start_time = Instant::now();
764
765 match self.rules.lock() {
766 Ok(mut rule_storage) => {
767 rule_storage.extend(rules.clone());
768
769 if let Ok(mut metrics) = self.metrics.lock() {
770 metrics.rules_processed += rules.len();
771 metrics.rule_loading_time += start_time.elapsed();
772 }
773
774 info!(
775 "Added {rule_count} rules to parallel engine",
776 rule_count = rules.len()
777 );
778 Ok(())
779 }
780 _ => Err("Failed to acquire rule storage lock".to_string()),
781 }
782 }
783
784 pub fn parallel_forward_chain(&mut self) -> Result<Vec<RuleAtom>, String> {
786 let start_time = Instant::now();
787 info!(
788 "Starting parallel forward chaining with {} threads",
789 self.num_threads
790 );
791
792 let rules = self.rules.clone();
794 let facts = self.facts.clone();
795 let metrics = self.metrics.clone();
796
797 let derived_facts = Arc::new(Mutex::new(Vec::new()));
798 let mut handles = Vec::new();
799
800 for thread_id in 0..self.num_threads {
802 let rules_clone = rules.clone();
803 let facts_clone = facts.clone();
804 let derived_facts_clone = derived_facts.clone();
805 let metrics_clone = metrics.clone();
806
807 let handle = thread::spawn(move || {
808 Self::worker_forward_chain(
809 thread_id,
810 rules_clone,
811 facts_clone,
812 derived_facts_clone,
813 metrics_clone,
814 );
815 });
816
817 handles.push(handle);
818 }
819
820 for handle in handles {
822 if let Err(e) = handle.join() {
823 warn!("Worker thread panicked: {:?}", e);
824 }
825 }
826
827 let results = match derived_facts.lock() {
829 Ok(derived) => derived.clone(),
830 _ => {
831 return Err("Failed to acquire derived facts lock".to_string());
832 }
833 };
834
835 if let Ok(mut metrics) = self.metrics.lock() {
837 metrics.forward_chaining_time += start_time.elapsed();
838 metrics.inferred_facts += results.len();
839 }
840
841 info!(
842 "Parallel forward chaining completed, derived {} facts",
843 results.len()
844 );
845 Ok(results)
846 }
847
848 fn worker_forward_chain(
850 thread_id: usize,
851 rules: Arc<Mutex<Vec<Rule>>>,
852 facts: Arc<Mutex<Vec<RuleAtom>>>,
853 derived_facts: Arc<Mutex<Vec<RuleAtom>>>,
854 _metrics: Arc<Mutex<PerformanceMetrics>>,
855 ) {
856 debug!("Worker thread {thread_id} starting forward chaining");
857
858 let mut local_engine = RuleEngine::new();
860
861 let (local_rules, local_facts) = {
863 let rules_guard = rules.lock().expect("lock should not be poisoned");
864 let facts_guard = facts.lock().expect("lock should not be poisoned");
865 (rules_guard.clone(), facts_guard.clone())
866 };
867
868 for rule in local_rules {
870 local_engine.add_rule(rule);
871 }
872
873 let chunk_size = (local_facts.len() + 3) / 4; let start_idx = thread_id * chunk_size;
876 let end_idx = std::cmp::min(start_idx + chunk_size, local_facts.len());
877
878 if start_idx < local_facts.len() {
879 let worker_facts = &local_facts[start_idx..end_idx];
880
881 match local_engine.forward_chain(worker_facts) {
882 Ok(new_facts) => {
883 if let Ok(mut derived) = derived_facts.lock() {
884 derived.extend(new_facts);
885 }
886 debug!(
887 "Worker thread {} processed {} facts",
888 thread_id,
889 worker_facts.len()
890 );
891 }
892 Err(e) => {
893 warn!("Worker thread {thread_id} failed: {e}");
894 }
895 }
896 }
897 }
898
899 pub fn get_metrics(&self) -> PerformanceMetrics {
901 match self.metrics.lock() {
902 Ok(metrics) => metrics.clone(),
903 _ => {
904 warn!("Failed to acquire metrics lock");
905 PerformanceMetrics {
906 total_time: Duration::new(0, 0),
907 rule_loading_time: Duration::new(0, 0),
908 fact_processing_time: Duration::new(0, 0),
909 forward_chaining_time: Duration::new(0, 0),
910 backward_chaining_time: Duration::new(0, 0),
911 rules_processed: 0,
912 facts_processed: 0,
913 inferred_facts: 0,
914 memory_stats: MemoryStats {
915 peak_memory_usage: 0,
916 facts_memory: 0,
917 rules_memory: 0,
918 derived_facts_memory: 0,
919 },
920 rule_timings: HashMap::new(),
921 warnings: Vec::new(),
922 }
923 }
924 }
925 }
926}
927
928impl Default for ParallelRuleEngine {
929 fn default() -> Self {
930 Self::new(None)
931 }
932}
933
934pub struct IncrementalReasoningEngine {
936 base_engine: Arc<Mutex<RuleEngine>>,
938 fact_dependencies: Arc<Mutex<HashMap<RuleAtom, Vec<RuleAtom>>>>,
940 rule_activations: Arc<Mutex<HashMap<String, Vec<RuleAtom>>>>,
942 materialized_facts: Arc<Mutex<Vec<RuleAtom>>>,
944 change_tracker: Arc<Mutex<ChangeTracker>>,
946 incremental_metrics: Arc<Mutex<IncrementalMetrics>>,
948}
949
950#[derive(Debug, Clone, Default)]
952pub struct ChangeTracker {
953 added_facts: Vec<RuleAtom>,
955 #[allow(dead_code)]
957 removed_facts: Vec<RuleAtom>,
958 #[allow(dead_code)]
960 affected_rules: Vec<String>,
961 #[allow(dead_code)]
963 last_reasoning_time: Option<std::time::Instant>,
964}
965
966#[derive(Debug, Clone, Default)]
968pub struct IncrementalMetrics {
969 pub incremental_updates: usize,
971 pub time_saved: Duration,
973 pub facts_reused: usize,
975 pub rules_skipped: usize,
977 pub avg_update_time: Duration,
979}
980
981impl IncrementalReasoningEngine {
982 pub fn new() -> Self {
984 Self {
985 base_engine: Arc::new(Mutex::new(RuleEngine::new())),
986 fact_dependencies: Arc::new(Mutex::new(HashMap::new())),
987 rule_activations: Arc::new(Mutex::new(HashMap::new())),
988 materialized_facts: Arc::new(Mutex::new(Vec::new())),
989 change_tracker: Arc::new(Mutex::new(ChangeTracker::default())),
990 incremental_metrics: Arc::new(Mutex::new(IncrementalMetrics::default())),
991 }
992 }
993
994 pub fn add_rules(&mut self, rules: Vec<Rule>) -> Result<(), String> {
996 info!(
997 "Adding {} rules to incremental reasoning engine",
998 rules.len()
999 );
1000
1001 match self.base_engine.lock() {
1002 Ok(mut engine) => {
1003 for rule in rules {
1004 engine.add_rule(rule);
1005 }
1006 Ok(())
1007 }
1008 _ => Err("Failed to acquire engine lock".to_string()),
1009 }
1010 }
1011
1012 pub fn add_facts_incremental(
1014 &mut self,
1015 new_facts: Vec<RuleAtom>,
1016 ) -> Result<Vec<RuleAtom>, String> {
1017 let start_time = Instant::now();
1018 info!(
1019 "Starting incremental reasoning with {} new facts",
1020 new_facts.len()
1021 );
1022
1023 if let Ok(mut tracker) = self.change_tracker.lock() {
1025 tracker.added_facts.extend(new_facts.clone());
1026 }
1027
1028 let affected_rules = self.identify_affected_rules(&new_facts)?;
1030 info!(
1031 "Identified {rule_count} affected rules",
1032 rule_count = affected_rules.len()
1033 );
1034
1035 let new_derived_facts = self.reason_incrementally(new_facts, affected_rules)?;
1037
1038 if let Ok(mut materialized) = self.materialized_facts.lock() {
1040 materialized.extend(new_derived_facts.clone());
1041 }
1042
1043 if let Ok(mut metrics) = self.incremental_metrics.lock() {
1045 metrics.incremental_updates += 1;
1046 metrics.avg_update_time = if metrics.incremental_updates == 1 {
1047 start_time.elapsed()
1048 } else {
1049 Duration::from_nanos(
1050 (metrics.avg_update_time.as_nanos() as u64
1051 + start_time.elapsed().as_nanos() as u64)
1052 / 2,
1053 )
1054 };
1055 }
1056
1057 info!(
1058 "Incremental reasoning completed, derived {} new facts in {:?}",
1059 new_derived_facts.len(),
1060 start_time.elapsed()
1061 );
1062
1063 Ok(new_derived_facts)
1064 }
1065
1066 fn identify_affected_rules(&self, new_facts: &[RuleAtom]) -> Result<Vec<String>, String> {
1068 let mut affected_rules = Vec::new();
1069
1070 if let Ok(engine) = self.base_engine.lock() {
1071 for rule in &engine.rules {
1072 for new_fact in new_facts {
1073 if self.rule_could_match_fact(rule, new_fact) {
1074 affected_rules.push(rule.name.clone());
1075 break; }
1077 }
1078 }
1079 }
1080
1081 Ok(affected_rules)
1082 }
1083
1084 fn rule_could_match_fact(&self, rule: &Rule, fact: &RuleAtom) -> bool {
1086 for body_atom in &rule.body {
1088 if self.atoms_could_unify(body_atom, fact) {
1089 return true;
1090 }
1091 }
1092 false
1093 }
1094
1095 fn atoms_could_unify(&self, atom1: &RuleAtom, atom2: &RuleAtom) -> bool {
1097 match (atom1, atom2) {
1098 (
1099 RuleAtom::Triple {
1100 subject: s1,
1101 predicate: p1,
1102 object: o1,
1103 },
1104 RuleAtom::Triple {
1105 subject: s2,
1106 predicate: p2,
1107 object: o2,
1108 },
1109 ) => {
1110 self.terms_could_unify(s1, s2)
1111 && self.terms_could_unify(p1, p2)
1112 && self.terms_could_unify(o1, o2)
1113 }
1114 (
1115 RuleAtom::Builtin { name: n1, args: a1 },
1116 RuleAtom::Builtin { name: n2, args: a2 },
1117 ) => {
1118 n1 == n2
1119 && a1.len() == a2.len()
1120 && a1
1121 .iter()
1122 .zip(a2.iter())
1123 .all(|(t1, t2)| self.terms_could_unify(t1, t2))
1124 }
1125 _ => false,
1126 }
1127 }
1128
1129 fn terms_could_unify(&self, term1: &Term, term2: &Term) -> bool {
1131 match (term1, term2) {
1132 (Term::Variable(_), _) | (_, Term::Variable(_)) => true,
1133 (Term::Constant(c1), Term::Constant(c2)) => c1 == c2,
1134 (Term::Literal(l1), Term::Literal(l2)) => l1 == l2,
1135 _ => false,
1136 }
1137 }
1138
1139 fn reason_incrementally(
1141 &mut self,
1142 new_facts: Vec<RuleAtom>,
1143 affected_rules: Vec<String>,
1144 ) -> Result<Vec<RuleAtom>, String> {
1145 let mut derived_facts = Vec::new();
1146
1147 if let Ok(mut engine) = self.base_engine.lock() {
1148 engine.add_facts(new_facts.clone());
1150
1151 for rule_name in &affected_rules {
1153 if let Some(rule) = engine.rules.iter().find(|r| r.name == *rule_name) {
1154 let mut temp_engine = RuleEngine::new();
1156 temp_engine.add_rule(rule.clone());
1157 temp_engine.add_facts(engine.get_facts());
1158
1159 match temp_engine.forward_chain(&[]) {
1160 Ok(rule_derived) => {
1161 let new_derived: Vec<RuleAtom> = rule_derived
1163 .into_iter()
1164 .filter(|fact| !self.fact_already_known(fact))
1165 .collect();
1166
1167 derived_facts.extend(new_derived);
1168 }
1169 Err(e) => {
1170 warn!("Failed to apply rule '{rule_name}': {e}");
1171 }
1172 }
1173 }
1174 }
1175
1176 if let Ok(mut metrics) = self.incremental_metrics.lock() {
1178 let total_rules = engine.rules.len();
1179 metrics.rules_skipped += total_rules.saturating_sub(affected_rules.len());
1180 }
1181 }
1182
1183 Ok(derived_facts)
1184 }
1185
1186 fn fact_already_known(&self, fact: &RuleAtom) -> bool {
1188 match self.materialized_facts.lock() {
1189 Ok(materialized) => materialized.contains(fact),
1190 _ => {
1191 false }
1193 }
1194 }
1195
1196 pub fn get_incremental_metrics(&self) -> IncrementalMetrics {
1198 match self.incremental_metrics.lock() {
1199 Ok(metrics) => metrics.clone(),
1200 _ => {
1201 warn!("Failed to acquire metrics lock");
1202 IncrementalMetrics::default()
1203 }
1204 }
1205 }
1206
1207 pub fn reset(&mut self) {
1209 info!("Resetting incremental reasoning engine");
1210
1211 if let Ok(mut materialized) = self.materialized_facts.lock() {
1212 materialized.clear();
1213 }
1214
1215 if let Ok(mut dependencies) = self.fact_dependencies.lock() {
1216 dependencies.clear();
1217 }
1218
1219 if let Ok(mut activations) = self.rule_activations.lock() {
1220 activations.clear();
1221 }
1222
1223 if let Ok(mut tracker) = self.change_tracker.lock() {
1224 *tracker = ChangeTracker::default();
1225 }
1226
1227 if let Ok(mut metrics) = self.incremental_metrics.lock() {
1228 *metrics = IncrementalMetrics::default();
1229 }
1230 }
1231
1232 pub fn full_reasoning_with_cache(
1234 &mut self,
1235 facts: Vec<RuleAtom>,
1236 ) -> Result<Vec<RuleAtom>, String> {
1237 let start_time = Instant::now();
1238 info!(
1239 "Performing full reasoning with caching for {} facts",
1240 facts.len()
1241 );
1242
1243 match self.base_engine.lock() {
1244 Ok(mut engine) => {
1245 engine.clear();
1246 engine.add_facts(facts);
1247
1248 match engine.forward_chain(&[]) {
1249 Ok(derived_facts) => {
1250 if let Ok(mut materialized) = self.materialized_facts.lock() {
1252 materialized.clear();
1253 materialized.extend(derived_facts.clone());
1254 }
1255
1256 self.build_dependency_graph(&derived_facts)?;
1258
1259 info!(
1260 "Full reasoning completed in {:?}, cached {} facts",
1261 start_time.elapsed(),
1262 derived_facts.len()
1263 );
1264
1265 Ok(derived_facts)
1266 }
1267 Err(e) => Err(format!("Full reasoning failed: {e}")),
1268 }
1269 }
1270 _ => Err("Failed to acquire engine lock".to_string()),
1271 }
1272 }
1273
1274 fn build_dependency_graph(&self, derived_facts: &[RuleAtom]) -> Result<(), String> {
1276 if let Ok(mut dependencies) = self.fact_dependencies.lock() {
1277 dependencies.clear();
1278
1279 for fact in derived_facts {
1282 dependencies.insert(fact.clone(), vec![]);
1283 }
1284 }
1285
1286 Ok(())
1287 }
1288
1289 pub fn benchmark_incremental_vs_full(
1291 &mut self,
1292 initial_facts: Vec<RuleAtom>,
1293 new_facts: Vec<RuleAtom>,
1294 ) -> Result<BenchmarkResults, String> {
1295 info!("Benchmarking incremental vs full reasoning");
1296
1297 let full_start = Instant::now();
1299 let mut all_facts = initial_facts.clone();
1300 all_facts.extend(new_facts.clone());
1301 self.full_reasoning_with_cache(all_facts)?;
1302 let full_time = full_start.elapsed();
1303
1304 self.reset();
1306 self.full_reasoning_with_cache(initial_facts)?;
1307
1308 let incremental_start = Instant::now();
1310 let incremental_results = self.add_facts_incremental(new_facts)?;
1311 let incremental_time = incremental_start.elapsed();
1312
1313 let speedup = if incremental_time.as_nanos() > 0 {
1314 full_time.as_nanos() as f64 / incremental_time.as_nanos() as f64
1315 } else {
1316 f64::INFINITY
1317 };
1318
1319 let results = BenchmarkResults {
1320 full_reasoning_time: full_time,
1321 incremental_reasoning_time: incremental_time,
1322 speedup_factor: speedup,
1323 facts_derived: incremental_results.len(),
1324 };
1325
1326 info!("Benchmark results: {results:?}");
1327 Ok(results)
1328 }
1329}
1330
1331impl Default for IncrementalReasoningEngine {
1332 fn default() -> Self {
1333 Self::new()
1334 }
1335}
1336
1337#[derive(Debug, Clone)]
1339pub struct BenchmarkResults {
1340 pub full_reasoning_time: Duration,
1341 pub incremental_reasoning_time: Duration,
1342 pub speedup_factor: f64,
1343 pub facts_derived: usize,
1344}
1345
1346impl std::fmt::Display for BenchmarkResults {
1347 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1348 write!(
1349 f,
1350 "Benchmark: Full {:?} vs Incremental {:?} = {:.2}x speedup ({} facts)",
1351 self.full_reasoning_time,
1352 self.incremental_reasoning_time,
1353 self.speedup_factor,
1354 self.facts_derived
1355 )
1356 }
1357}
1358
1359impl std::fmt::Display for IncrementalMetrics {
1360 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1361 write!(
1362 f,
1363 "Incremental: {} updates, avg {:?}, {} facts reused, {} rules skipped",
1364 self.incremental_updates, self.avg_update_time, self.facts_reused, self.rules_skipped
1365 )
1366 }
1367}
1368
1369pub struct HybridReasoningEngine {
1371 parallel_engine: ParallelRuleEngine,
1372 incremental_engine: IncrementalReasoningEngine,
1373 strategy: ReasoningStrategy,
1374 performance_monitor: Arc<Mutex<PerformanceMetrics>>,
1375}
1376
1377#[derive(Debug, Clone)]
1379pub enum ReasoningStrategy {
1380 AlwaysParallel,
1382 AlwaysIncremental,
1384 Adaptive {
1386 parallel_threshold: usize,
1388 complexity_threshold: usize,
1390 },
1391}
1392
1393impl HybridReasoningEngine {
1394 pub fn new(strategy: ReasoningStrategy) -> Self {
1396 Self {
1397 parallel_engine: ParallelRuleEngine::new(None),
1398 incremental_engine: IncrementalReasoningEngine::new(),
1399 strategy,
1400 performance_monitor: Arc::new(Mutex::new(PerformanceMetrics {
1401 total_time: Duration::new(0, 0),
1402 rule_loading_time: Duration::new(0, 0),
1403 fact_processing_time: Duration::new(0, 0),
1404 forward_chaining_time: Duration::new(0, 0),
1405 backward_chaining_time: Duration::new(0, 0),
1406 rules_processed: 0,
1407 facts_processed: 0,
1408 inferred_facts: 0,
1409 memory_stats: MemoryStats {
1410 peak_memory_usage: 0,
1411 facts_memory: 0,
1412 rules_memory: 0,
1413 derived_facts_memory: 0,
1414 },
1415 rule_timings: HashMap::new(),
1416 warnings: Vec::new(),
1417 })),
1418 }
1419 }
1420
1421 pub fn add_rules(&mut self, rules: Vec<Rule>) -> Result<(), String> {
1423 self.parallel_engine.add_rules(rules.clone())?;
1424 self.incremental_engine.add_rules(rules)?;
1425 Ok(())
1426 }
1427
1428 pub fn reason(&mut self, new_facts: Vec<RuleAtom>) -> Result<Vec<RuleAtom>, String> {
1430 let start_time = Instant::now();
1431
1432 let strategy_choice = match &self.strategy {
1433 ReasoningStrategy::AlwaysParallel => "parallel",
1434 ReasoningStrategy::AlwaysIncremental => "incremental",
1435 ReasoningStrategy::Adaptive {
1436 parallel_threshold,
1437 complexity_threshold,
1438 } => {
1439 if new_facts.len() > *parallel_threshold
1440 || self.estimate_rule_complexity()? > *complexity_threshold
1441 {
1442 "parallel"
1443 } else {
1444 "incremental"
1445 }
1446 }
1447 };
1448
1449 info!(
1450 "Using {} reasoning strategy for {} facts",
1451 strategy_choice,
1452 new_facts.len()
1453 );
1454
1455 let results = match strategy_choice {
1456 "parallel" => {
1457 if let Ok(mut facts) = self.parallel_engine.facts.lock() {
1459 facts.extend(new_facts);
1460 }
1461 self.parallel_engine.parallel_forward_chain()
1462 }
1463 "incremental" => self.incremental_engine.add_facts_incremental(new_facts),
1464 _ => unreachable!(),
1465 };
1466
1467 if let Ok(mut metrics) = self.performance_monitor.lock() {
1469 metrics.total_time += start_time.elapsed();
1470 if let Ok(ref result_facts) = results {
1471 metrics.inferred_facts += result_facts.len();
1472 }
1473 }
1474
1475 results
1476 }
1477
1478 fn estimate_rule_complexity(&self) -> Result<usize, String> {
1480 Ok(100) }
1484
1485 pub fn get_performance_metrics(&self) -> PerformanceMetrics {
1487 match self.performance_monitor.lock() {
1488 Ok(metrics) => metrics.clone(),
1489 _ => {
1490 warn!("Failed to acquire performance monitor lock");
1491 PerformanceMetrics {
1492 total_time: Duration::new(0, 0),
1493 rule_loading_time: Duration::new(0, 0),
1494 fact_processing_time: Duration::new(0, 0),
1495 forward_chaining_time: Duration::new(0, 0),
1496 backward_chaining_time: Duration::new(0, 0),
1497 rules_processed: 0,
1498 facts_processed: 0,
1499 inferred_facts: 0,
1500 memory_stats: MemoryStats {
1501 peak_memory_usage: 0,
1502 facts_memory: 0,
1503 rules_memory: 0,
1504 derived_facts_memory: 0,
1505 },
1506 rule_timings: HashMap::new(),
1507 warnings: Vec::new(),
1508 }
1509 }
1510 }
1511 }
1512
1513 pub fn get_strategy_breakdown(&self) -> String {
1515 format!("Strategy: {:?}", self.strategy)
1516 }
1517}
1518
1519impl Default for HybridReasoningEngine {
1520 fn default() -> Self {
1521 Self::new(ReasoningStrategy::Adaptive {
1522 parallel_threshold: 1000,
1523 complexity_threshold: 50,
1524 })
1525 }
1526}