Skip to main content

oxirs_rule/
debug.rs

1//! # Rule Engine Debugging Tools
2//!
3//! Advanced debugging capabilities for rule engines including execution visualization,
4//! derivation path tracing, performance profiling, and conflict detection.
5
6use anyhow::{anyhow, Result};
7use serde::{Deserialize, Serialize};
8use std::collections::{HashMap, HashSet};
9use std::fmt::{self, Display};
10use std::time::{Duration, Instant};
11
12use crate::{RuleAtom, RuleEngine};
13
14/// Debug trace entry recording rule execution steps
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct TraceEntry {
17    pub timestamp: u64,
18    pub rule_name: String,
19    pub action: TraceAction,
20    pub input_facts: Vec<RuleAtom>,
21    pub output_facts: Vec<RuleAtom>,
22    pub duration: Duration,
23    pub memory_usage: usize,
24}
25
26/// Types of trace actions
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub enum TraceAction {
29    RuleExecution,
30    FactAddition,
31    Unification,
32    BackwardChaining,
33    ForwardChaining,
34    ReteActivation,
35}
36
37/// Derivation path showing how a fact was derived
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct DerivationPath {
40    pub target_fact: RuleAtom,
41    pub steps: Vec<DerivationStep>,
42    pub total_depth: usize,
43    pub involved_rules: HashSet<String>,
44}
45
46/// Single step in a derivation path
47#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct DerivationStep {
49    pub rule_name: String,
50    pub premises: Vec<RuleAtom>,
51    pub conclusion: RuleAtom,
52    pub unification: HashMap<String, String>,
53    pub step_number: usize,
54}
55
56/// Performance metrics for rule execution
57#[derive(Debug, Clone, Serialize, Deserialize)]
58pub struct PerformanceMetrics {
59    pub total_execution_time: Duration,
60    pub rule_execution_times: HashMap<String, Duration>,
61    pub rule_execution_counts: HashMap<String, usize>,
62    pub facts_processed: usize,
63    pub facts_derived: usize,
64    pub memory_peak: usize,
65    pub cache_hits: usize,
66    pub cache_misses: usize,
67}
68
69/// Rule conflict detection and analysis
70#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct RuleConflict {
72    pub conflict_type: ConflictType,
73    pub involved_rules: Vec<String>,
74    pub conflicting_facts: Vec<RuleAtom>,
75    pub severity: ConflictSeverity,
76    pub resolution_suggestion: String,
77}
78
79/// Types of rule conflicts
80#[derive(Debug, Clone, Serialize, Deserialize)]
81pub enum ConflictType {
82    ContradictoryConclusions,
83    CircularDependency,
84    RedundantRules,
85    UnreachableRules,
86    PerformanceBottleneck,
87}
88
89/// Severity levels for conflicts
90#[derive(Debug, Clone, Serialize, Deserialize)]
91pub enum ConflictSeverity {
92    Critical,
93    Warning,
94    Info,
95}
96
97/// Debugger state
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum DebuggerState {
100    /// Running normally
101    Running,
102    /// Paused at breakpoint
103    Paused,
104    /// Stepping through execution
105    Stepping,
106    /// Execution complete
107    Finished,
108}
109
110/// Debug command for interactive debugging
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub enum DebugCommand {
113    /// Continue execution until next breakpoint
114    Continue,
115    /// Step to next rule execution
116    Step,
117    /// Step over current rule (execute without entering)
118    Next,
119    /// Step out of current rule
120    StepOut,
121    /// Print current state
122    Print,
123    /// List breakpoints
124    ListBreakpoints,
125    /// Show call stack
126    Backtrace,
127    /// Quit debugging
128    Quit,
129}
130
131/// Stack frame for call stack tracking
132#[derive(Debug, Clone)]
133pub struct StackFrame {
134    /// Rule name
135    pub rule_name: String,
136    /// Current substitutions
137    pub substitutions: HashMap<String, String>,
138    /// Input facts for this frame
139    pub input_facts: Vec<RuleAtom>,
140    /// Frame depth
141    pub depth: usize,
142}
143
144/// Watch expression for monitoring values
145#[derive(Debug, Clone)]
146pub struct WatchExpression {
147    /// Expression name/description
148    pub name: String,
149    /// Variable to watch
150    pub variable: String,
151    /// Last known value
152    pub last_value: Option<String>,
153    /// Break when value changes
154    pub break_on_change: bool,
155}
156
157/// Conditional breakpoint
158#[derive(Debug, Clone)]
159pub struct ConditionalBreakpoint {
160    /// Rule name to break on
161    pub rule_name: String,
162    /// Condition that must be true (variable = value)
163    pub condition: Option<BreakpointCondition>,
164    /// Hit count (break after N hits)
165    pub hit_count: Option<usize>,
166    /// Current hit count
167    pub current_hits: usize,
168    /// Is breakpoint enabled
169    pub enabled: bool,
170}
171
172/// Breakpoint condition
173#[derive(Debug, Clone)]
174pub struct BreakpointCondition {
175    /// Variable name
176    pub variable: String,
177    /// Expected value
178    pub value: String,
179    /// Comparison operator
180    pub operator: ConditionOperator,
181}
182
183/// Condition operator
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub enum ConditionOperator {
186    /// Equal
187    Equals,
188    /// Not equal
189    NotEquals,
190    /// Contains substring
191    Contains,
192}
193
194/// Interactive debugging session
195#[derive(Debug)]
196pub struct DebugSession {
197    pub trace: Vec<TraceEntry>,
198    pub derivations: HashMap<String, DerivationPath>,
199    pub metrics: PerformanceMetrics,
200    pub conflicts: Vec<RuleConflict>,
201    pub breakpoints: HashSet<String>,
202    pub step_mode: bool,
203    pub current_step: usize,
204    /// Debugger state
205    pub state: DebuggerState,
206    /// Call stack
207    pub call_stack: Vec<StackFrame>,
208    /// Conditional breakpoints
209    pub conditional_breakpoints: Vec<ConditionalBreakpoint>,
210    /// Watch expressions
211    pub watch_expressions: Vec<WatchExpression>,
212    /// Current substitutions (variable bindings)
213    pub current_substitutions: HashMap<String, String>,
214    /// Paused events queue (for async notification)
215    pub paused_events: Vec<String>,
216}
217
218/// Enhanced rule engine with debugging capabilities
219#[derive(Debug)]
220pub struct DebuggableRuleEngine {
221    pub engine: RuleEngine,
222    pub debug_session: DebugSession,
223    pub debug_enabled: bool,
224}
225
226impl Default for DebuggableRuleEngine {
227    fn default() -> Self {
228        Self::new()
229    }
230}
231
232impl DebuggableRuleEngine {
233    /// Create a new debuggable rule engine
234    pub fn new() -> Self {
235        Self {
236            engine: RuleEngine::new(),
237            debug_session: DebugSession::new(),
238            debug_enabled: false,
239        }
240    }
241
242    /// Enable debugging with optional configuration
243    pub fn enable_debugging(&mut self, step_mode: bool) {
244        self.debug_enabled = true;
245        self.debug_session.step_mode = step_mode;
246        self.debug_session.clear();
247    }
248
249    /// Disable debugging
250    pub fn disable_debugging(&mut self) {
251        self.debug_enabled = false;
252        self.debug_session.clear();
253    }
254
255    /// Add a breakpoint on a specific rule
256    pub fn add_breakpoint(&mut self, rule_name: &str) {
257        self.debug_session.breakpoints.insert(rule_name.to_string());
258    }
259
260    /// Remove a breakpoint
261    pub fn remove_breakpoint(&mut self, rule_name: &str) {
262        self.debug_session.breakpoints.remove(rule_name);
263    }
264
265    /// Execute forward chaining with debugging
266    pub fn debug_forward_chain(&mut self, facts: &[RuleAtom]) -> Result<Vec<RuleAtom>> {
267        if !self.debug_enabled {
268            return self.engine.forward_chain(facts);
269        }
270
271        let start_time = Instant::now();
272        let initial_memory = self.estimate_memory_usage();
273
274        // Record fact addition
275        self.record_trace_entry(TraceEntry {
276            timestamp: self.current_timestamp(),
277            rule_name: "__fact_addition__".to_string(),
278            action: TraceAction::FactAddition,
279            input_facts: vec![],
280            output_facts: facts.to_vec(),
281            duration: Duration::from_nanos(0),
282            memory_usage: initial_memory,
283        });
284
285        // Execute with tracing
286        let result = self.traced_forward_chain(facts)?;
287
288        // Update metrics
289        self.debug_session.metrics.total_execution_time = start_time.elapsed();
290        self.debug_session.metrics.facts_processed = facts.len();
291        self.debug_session.metrics.facts_derived = result.len() - facts.len();
292        self.debug_session.metrics.memory_peak = self.estimate_memory_usage();
293
294        // Analyze for conflicts
295        self.analyze_conflicts();
296
297        Ok(result)
298    }
299
300    /// Execute backward chaining with debugging
301    pub fn debug_backward_chain(&mut self, goal: &RuleAtom) -> Result<bool> {
302        if !self.debug_enabled {
303            return self.engine.backward_chain(goal);
304        }
305
306        let start_time = Instant::now();
307
308        // Build derivation path
309        let derivation = self.build_derivation_path(goal)?;
310        if let Some(path) = derivation {
311            let goal_key = format!("{goal:?}");
312            self.debug_session.derivations.insert(goal_key, path);
313        }
314
315        let result = self.traced_backward_chain(goal)?;
316
317        // Record performance
318        let duration = start_time.elapsed();
319        self.record_trace_entry(TraceEntry {
320            timestamp: self.current_timestamp(),
321            rule_name: "__backward_chain__".to_string(),
322            action: TraceAction::BackwardChaining,
323            input_facts: vec![goal.clone()],
324            output_facts: if result { vec![goal.clone()] } else { vec![] },
325            duration,
326            memory_usage: self.estimate_memory_usage(),
327        });
328
329        Ok(result)
330    }
331
332    /// Get execution trace
333    pub fn get_trace(&self) -> &[TraceEntry] {
334        &self.debug_session.trace
335    }
336
337    /// Get derivation path for a fact
338    pub fn get_derivation(&self, fact: &RuleAtom) -> Option<&DerivationPath> {
339        let key = format!("{fact:?}");
340        self.debug_session.derivations.get(&key)
341    }
342
343    /// Get performance metrics
344    pub fn get_metrics(&self) -> &PerformanceMetrics {
345        &self.debug_session.metrics
346    }
347
348    /// Get detected conflicts
349    pub fn get_conflicts(&self) -> &[RuleConflict] {
350        &self.debug_session.conflicts
351    }
352
353    /// Generate debug report
354    pub fn generate_debug_report(&self) -> String {
355        let mut report = String::new();
356
357        report.push_str("=== RULE ENGINE DEBUG REPORT ===\n\n");
358
359        // Performance metrics
360        report.push_str("PERFORMANCE METRICS:\n");
361        report.push_str(&format!(
362            "Total execution time: {:?}\n",
363            self.debug_session.metrics.total_execution_time
364        ));
365        report.push_str(&format!(
366            "Facts processed: {}\n",
367            self.debug_session.metrics.facts_processed
368        ));
369        report.push_str(&format!(
370            "Facts derived: {}\n",
371            self.debug_session.metrics.facts_derived
372        ));
373        report.push_str(&format!(
374            "Memory peak: {} bytes\n",
375            self.debug_session.metrics.memory_peak
376        ));
377        report.push_str(&format!(
378            "Cache hits: {}\n",
379            self.debug_session.metrics.cache_hits
380        ));
381        report.push_str(&format!(
382            "Cache misses: {}\n",
383            self.debug_session.metrics.cache_misses
384        ));
385        report.push('\n');
386
387        // Rule execution times
388        report.push_str("RULE EXECUTION TIMES:\n");
389        let mut rule_times: Vec<_> = self
390            .debug_session
391            .metrics
392            .rule_execution_times
393            .iter()
394            .collect();
395        rule_times.sort_by(|a, b| b.1.cmp(a.1));
396        for (rule, time) in rule_times.iter().take(10) {
397            let count = self
398                .debug_session
399                .metrics
400                .rule_execution_counts
401                .get(*rule)
402                .unwrap_or(&0);
403            report.push_str(&format!("  {rule}: {time:?} (executed {count} times)\n"));
404        }
405        report.push('\n');
406
407        // Conflicts
408        if !self.debug_session.conflicts.is_empty() {
409            report.push_str("DETECTED CONFLICTS:\n");
410            for conflict in &self.debug_session.conflicts {
411                report.push_str(&format!(
412                    "  {:?} - {:?}: {}\n",
413                    conflict.severity, conflict.conflict_type, conflict.resolution_suggestion
414                ));
415            }
416            report.push('\n');
417        }
418
419        // Derivation paths
420        if !self.debug_session.derivations.is_empty() {
421            report.push_str("DERIVATION PATHS:\n");
422            for (fact, path) in &self.debug_session.derivations {
423                report.push_str(&format!("  Fact: {fact}\n"));
424                report.push_str(&format!("  Depth: {}\n", path.total_depth));
425                report.push_str(&format!(
426                    "  Rules involved: {}\n",
427                    path.involved_rules
428                        .iter()
429                        .cloned()
430                        .collect::<Vec<_>>()
431                        .join(", ")
432                ));
433                for step in &path.steps {
434                    report.push_str(&format!(
435                        "    Step {}: {} -> {:?}\n",
436                        step.step_number, step.rule_name, step.conclusion
437                    ));
438                }
439                report.push('\n');
440            }
441        }
442
443        report
444    }
445
446    /// Export debug data to JSON
447    pub fn export_debug_data(&self) -> Result<String> {
448        #[derive(Serialize)]
449        struct DebugData {
450            trace: Vec<TraceEntry>,
451            derivations: HashMap<String, DerivationPath>,
452            metrics: PerformanceMetrics,
453            conflicts: Vec<RuleConflict>,
454        }
455
456        let data = DebugData {
457            trace: self.debug_session.trace.clone(),
458            derivations: self.debug_session.derivations.clone(),
459            metrics: self.debug_session.metrics.clone(),
460            conflicts: self.debug_session.conflicts.clone(),
461        };
462
463        serde_json::to_string_pretty(&data)
464            .map_err(|e| anyhow!("Failed to serialize debug data: {}", e))
465    }
466
467    // Private implementation methods
468
469    fn traced_forward_chain(&mut self, facts: &[RuleAtom]) -> Result<Vec<RuleAtom>> {
470        // Implementation would integrate with the actual forward chaining
471        // For now, delegate to the underlying engine
472        self.engine.forward_chain(facts)
473    }
474
475    fn traced_backward_chain(&mut self, goal: &RuleAtom) -> Result<bool> {
476        // Implementation would integrate with the actual backward chaining
477        // For now, delegate to the underlying engine
478        self.engine.backward_chain(goal)
479    }
480
481    fn build_derivation_path(&self, goal: &RuleAtom) -> Result<Option<DerivationPath>> {
482        // Placeholder implementation - would build actual derivation tree
483        Ok(Some(DerivationPath {
484            target_fact: goal.clone(),
485            steps: vec![],
486            total_depth: 0,
487            involved_rules: HashSet::new(),
488        }))
489    }
490
491    fn analyze_conflicts(&mut self) {
492        // Analyze rule conflicts and populate conflicts vector
493        self.detect_circular_dependencies();
494        self.detect_contradictory_rules();
495        self.detect_redundant_rules();
496        self.detect_performance_bottlenecks();
497    }
498
499    fn detect_circular_dependencies(&mut self) {
500        // Implementation for detecting circular rule dependencies
501        // This would analyze the rule dependency graph
502    }
503
504    fn detect_contradictory_rules(&mut self) {
505        // Implementation for detecting contradictory rule conclusions
506    }
507
508    fn detect_redundant_rules(&mut self) {
509        // Implementation for detecting redundant rules
510    }
511
512    fn detect_performance_bottlenecks(&mut self) {
513        // Analyze performance metrics to identify bottlenecks
514        for (rule_name, duration) in &self.debug_session.metrics.rule_execution_times {
515            if duration.as_millis() > 100 {
516                // Threshold for slow rules
517                self.debug_session.conflicts.push(RuleConflict {
518                    conflict_type: ConflictType::PerformanceBottleneck,
519                    involved_rules: vec![rule_name.clone()],
520                    conflicting_facts: vec![],
521                    severity: ConflictSeverity::Warning,
522                    resolution_suggestion: format!(
523                        "Rule '{}' is slow ({}ms). Consider optimization.",
524                        rule_name,
525                        duration.as_millis()
526                    ),
527                });
528            }
529        }
530    }
531
532    fn record_trace_entry(&mut self, entry: TraceEntry) {
533        // Extract values before moving the entry
534        let rule_name = entry.rule_name.clone();
535        let duration = entry.duration;
536
537        self.debug_session.trace.push(entry);
538
539        // Update metrics
540        if let Some(current_count) = self
541            .debug_session
542            .metrics
543            .rule_execution_counts
544            .get_mut(&rule_name)
545        {
546            *current_count += 1;
547        } else {
548            self.debug_session
549                .metrics
550                .rule_execution_counts
551                .insert(rule_name.clone(), 1);
552        }
553
554        // Update timing
555        if let Some(current_time) = self
556            .debug_session
557            .metrics
558            .rule_execution_times
559            .get_mut(&rule_name)
560        {
561            *current_time += duration;
562        } else {
563            self.debug_session
564                .metrics
565                .rule_execution_times
566                .insert(rule_name, duration);
567        }
568    }
569
570    fn current_timestamp(&self) -> u64 {
571        std::time::SystemTime::now()
572            .duration_since(std::time::UNIX_EPOCH)
573            .unwrap_or_default()
574            .as_millis() as u64
575    }
576
577    fn estimate_memory_usage(&self) -> usize {
578        // Rough estimation of memory usage
579        std::mem::size_of::<RuleEngine>()
580            + self.debug_session.trace.len() * std::mem::size_of::<TraceEntry>()
581            + self.debug_session.derivations.len() * 1024 // Rough estimate
582    }
583}
584
585impl DebugSession {
586    fn new() -> Self {
587        Self {
588            trace: Vec::new(),
589            derivations: HashMap::new(),
590            metrics: PerformanceMetrics::default(),
591            conflicts: Vec::new(),
592            breakpoints: HashSet::new(),
593            step_mode: false,
594            current_step: 0,
595            state: DebuggerState::Running,
596            call_stack: Vec::new(),
597            conditional_breakpoints: Vec::new(),
598            watch_expressions: Vec::new(),
599            current_substitutions: HashMap::new(),
600            paused_events: Vec::new(),
601        }
602    }
603
604    fn clear(&mut self) {
605        self.trace.clear();
606        self.derivations.clear();
607        self.conflicts.clear();
608        self.metrics = PerformanceMetrics::default();
609        self.current_step = 0;
610        self.state = DebuggerState::Running;
611        self.call_stack.clear();
612        self.current_substitutions.clear();
613        self.paused_events.clear();
614        // Keep breakpoints and watch expressions
615    }
616}
617
618impl DebuggableRuleEngine {
619    /// Add a conditional breakpoint
620    pub fn add_conditional_breakpoint(
621        &mut self,
622        rule_name: &str,
623        condition: Option<BreakpointCondition>,
624        hit_count: Option<usize>,
625    ) {
626        self.debug_session
627            .conditional_breakpoints
628            .push(ConditionalBreakpoint {
629                rule_name: rule_name.to_string(),
630                condition,
631                hit_count,
632                current_hits: 0,
633                enabled: true,
634            });
635    }
636
637    /// Add a watch expression
638    pub fn add_watch(&mut self, name: &str, variable: &str, break_on_change: bool) {
639        self.debug_session.watch_expressions.push(WatchExpression {
640            name: name.to_string(),
641            variable: variable.to_string(),
642            last_value: None,
643            break_on_change,
644        });
645    }
646
647    /// Remove a watch expression
648    pub fn remove_watch(&mut self, name: &str) {
649        self.debug_session
650            .watch_expressions
651            .retain(|w| w.name != name);
652    }
653
654    /// Get current call stack
655    pub fn get_call_stack(&self) -> &[StackFrame] {
656        &self.debug_session.call_stack
657    }
658
659    /// Get current variable bindings
660    pub fn get_substitutions(&self) -> &HashMap<String, String> {
661        &self.debug_session.current_substitutions
662    }
663
664    /// Get value of a specific variable
665    pub fn get_variable(&self, name: &str) -> Option<&String> {
666        self.debug_session.current_substitutions.get(name)
667    }
668
669    /// Set a variable value (for debugging)
670    pub fn set_variable(&mut self, name: &str, value: &str) {
671        self.debug_session
672            .current_substitutions
673            .insert(name.to_string(), value.to_string());
674    }
675
676    /// Execute a debug command
677    pub fn execute_command(&mut self, command: DebugCommand) -> String {
678        match command {
679            DebugCommand::Continue => {
680                self.debug_session.state = DebuggerState::Running;
681                self.debug_session.step_mode = false;
682                "Continuing execution...".to_string()
683            }
684            DebugCommand::Step => {
685                self.debug_session.state = DebuggerState::Stepping;
686                self.debug_session.step_mode = true;
687                "Stepping to next rule...".to_string()
688            }
689            DebugCommand::Next => {
690                // Step over - execute current rule without entering
691                self.debug_session.state = DebuggerState::Stepping;
692                "Stepping over...".to_string()
693            }
694            DebugCommand::StepOut => {
695                // Step out of current frame
696                if !self.debug_session.call_stack.is_empty() {
697                    self.debug_session.call_stack.pop();
698                    "Stepping out of current frame...".to_string()
699                } else {
700                    "No frame to step out of".to_string()
701                }
702            }
703            DebugCommand::Print => self.format_current_state(),
704            DebugCommand::ListBreakpoints => self.format_breakpoints(),
705            DebugCommand::Backtrace => self.format_backtrace(),
706            DebugCommand::Quit => {
707                self.debug_session.state = DebuggerState::Finished;
708                "Quitting debugger...".to_string()
709            }
710        }
711    }
712
713    /// Check if execution should pause
714    pub fn should_pause(&self, rule_name: &str) -> bool {
715        // Check step mode
716        if self.debug_session.step_mode {
717            return true;
718        }
719
720        // Check simple breakpoints
721        if self.debug_session.breakpoints.contains(rule_name) {
722            return true;
723        }
724
725        // Check conditional breakpoints
726        for bp in &self.debug_session.conditional_breakpoints {
727            if bp.enabled && bp.rule_name == rule_name {
728                // Check hit count
729                if let Some(hit_count) = bp.hit_count {
730                    if bp.current_hits >= hit_count {
731                        continue;
732                    }
733                }
734
735                // Check condition
736                if let Some(ref condition) = bp.condition {
737                    if !self.evaluate_condition(condition) {
738                        continue;
739                    }
740                }
741
742                return true;
743            }
744        }
745
746        false
747    }
748
749    /// Evaluate a breakpoint condition
750    fn evaluate_condition(&self, condition: &BreakpointCondition) -> bool {
751        if let Some(value) = self
752            .debug_session
753            .current_substitutions
754            .get(&condition.variable)
755        {
756            match condition.operator {
757                ConditionOperator::Equals => value == &condition.value,
758                ConditionOperator::NotEquals => value != &condition.value,
759                ConditionOperator::Contains => value.contains(&condition.value),
760            }
761        } else {
762            false
763        }
764    }
765
766    /// Push a stack frame
767    pub fn push_frame(&mut self, rule_name: &str, input_facts: Vec<RuleAtom>) {
768        let depth = self.debug_session.call_stack.len();
769        self.debug_session.call_stack.push(StackFrame {
770            rule_name: rule_name.to_string(),
771            substitutions: self.debug_session.current_substitutions.clone(),
772            input_facts,
773            depth,
774        });
775    }
776
777    /// Pop a stack frame
778    pub fn pop_frame(&mut self) -> Option<StackFrame> {
779        self.debug_session.call_stack.pop()
780    }
781
782    /// Update substitutions
783    pub fn update_substitutions(&mut self, substitutions: HashMap<String, String>) {
784        // Check watch expressions for changes
785        for watch in &mut self.debug_session.watch_expressions {
786            if let Some(new_value) = substitutions.get(&watch.variable) {
787                let changed = watch.last_value.as_ref() != Some(new_value);
788                if changed && watch.break_on_change {
789                    self.debug_session.paused_events.push(format!(
790                        "Watch '{}' changed: {:?} -> {}",
791                        watch.name, watch.last_value, new_value
792                    ));
793                    self.debug_session.state = DebuggerState::Paused;
794                }
795                watch.last_value = Some(new_value.clone());
796            }
797        }
798
799        self.debug_session.current_substitutions = substitutions;
800    }
801
802    /// Format current debugger state
803    fn format_current_state(&self) -> String {
804        let mut output = String::new();
805
806        output.push_str("=== Current State ===\n");
807        output.push_str(&format!("Debugger: {:?}\n", self.debug_session.state));
808        output.push_str(&format!("Step: {}\n", self.debug_session.current_step));
809
810        output.push_str("\nVariables:\n");
811        for (name, value) in &self.debug_session.current_substitutions {
812            output.push_str(&format!("  {} = {}\n", name, value));
813        }
814
815        if !self.debug_session.watch_expressions.is_empty() {
816            output.push_str("\nWatches:\n");
817            for watch in &self.debug_session.watch_expressions {
818                output.push_str(&format!(
819                    "  {}: {} = {:?}\n",
820                    watch.name, watch.variable, watch.last_value
821                ));
822            }
823        }
824
825        output
826    }
827
828    /// Format breakpoints list
829    fn format_breakpoints(&self) -> String {
830        let mut output = String::new();
831        output.push_str("=== Breakpoints ===\n");
832
833        // Simple breakpoints
834        for bp in &self.debug_session.breakpoints {
835            output.push_str(&format!("  {} (simple)\n", bp));
836        }
837
838        // Conditional breakpoints
839        for (i, bp) in self
840            .debug_session
841            .conditional_breakpoints
842            .iter()
843            .enumerate()
844        {
845            let status = if bp.enabled { "enabled" } else { "disabled" };
846            let condition = bp
847                .condition
848                .as_ref()
849                .map(|c| format!(" when {} {:?} {}", c.variable, c.operator, c.value))
850                .unwrap_or_default();
851            let hit_info = bp
852                .hit_count
853                .map(|h| format!(" (hit {}/{})", bp.current_hits, h))
854                .unwrap_or_default();
855
856            output.push_str(&format!(
857                "  [{}] {}{}{} ({})\n",
858                i, bp.rule_name, condition, hit_info, status
859            ));
860        }
861
862        output
863    }
864
865    /// Format call stack backtrace
866    fn format_backtrace(&self) -> String {
867        let mut output = String::new();
868        output.push_str("=== Call Stack ===\n");
869
870        for (i, frame) in self.debug_session.call_stack.iter().rev().enumerate() {
871            output.push_str(&format!(
872                "  #{} {} (depth: {})\n",
873                i, frame.rule_name, frame.depth
874            ));
875
876            if !frame.substitutions.is_empty() {
877                output.push_str("    Bindings:\n");
878                for (var, val) in &frame.substitutions {
879                    output.push_str(&format!("      {} = {}\n", var, val));
880                }
881            }
882        }
883
884        if self.debug_session.call_stack.is_empty() {
885            output.push_str("  (empty)\n");
886        }
887
888        output
889    }
890
891    /// Get debugger state
892    pub fn get_state(&self) -> DebuggerState {
893        self.debug_session.state
894    }
895
896    /// Check if debugger is paused
897    pub fn is_paused(&self) -> bool {
898        self.debug_session.state == DebuggerState::Paused
899    }
900
901    /// Get paused events
902    pub fn get_paused_events(&mut self) -> Vec<String> {
903        std::mem::take(&mut self.debug_session.paused_events)
904    }
905
906    /// Increment hit counter for conditional breakpoint
907    pub fn increment_hit_count(&mut self, rule_name: &str) {
908        for bp in &mut self.debug_session.conditional_breakpoints {
909            if bp.rule_name == rule_name {
910                bp.current_hits += 1;
911            }
912        }
913    }
914
915    /// Reset hit counts for all breakpoints
916    pub fn reset_hit_counts(&mut self) {
917        for bp in &mut self.debug_session.conditional_breakpoints {
918            bp.current_hits = 0;
919        }
920    }
921
922    /// Enable/disable a conditional breakpoint
923    pub fn set_breakpoint_enabled(&mut self, index: usize, enabled: bool) -> bool {
924        if let Some(bp) = self.debug_session.conditional_breakpoints.get_mut(index) {
925            bp.enabled = enabled;
926            true
927        } else {
928            false
929        }
930    }
931}
932
933impl Default for PerformanceMetrics {
934    fn default() -> Self {
935        Self {
936            total_execution_time: Duration::from_nanos(0),
937            rule_execution_times: HashMap::new(),
938            rule_execution_counts: HashMap::new(),
939            facts_processed: 0,
940            facts_derived: 0,
941            memory_peak: 0,
942            cache_hits: 0,
943            cache_misses: 0,
944        }
945    }
946}
947
948impl Display for ConflictType {
949    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
950        match self {
951            ConflictType::ContradictoryConclusions => write!(f, "Contradictory Conclusions"),
952            ConflictType::CircularDependency => write!(f, "Circular Dependency"),
953            ConflictType::RedundantRules => write!(f, "Redundant Rules"),
954            ConflictType::UnreachableRules => write!(f, "Unreachable Rules"),
955            ConflictType::PerformanceBottleneck => write!(f, "Performance Bottleneck"),
956        }
957    }
958}
959
960impl Display for ConflictSeverity {
961    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
962        match self {
963            ConflictSeverity::Critical => write!(f, "CRITICAL"),
964            ConflictSeverity::Warning => write!(f, "WARNING"),
965            ConflictSeverity::Info => write!(f, "INFO"),
966        }
967    }
968}
969
970#[cfg(test)]
971mod tests {
972    use super::*;
973
974    #[test]
975    fn test_debuggable_engine_creation() {
976        let engine = DebuggableRuleEngine::new();
977        assert!(!engine.debug_enabled);
978        assert!(engine.debug_session.trace.is_empty());
979    }
980
981    #[test]
982    fn test_debugging_enable_disable() {
983        let mut engine = DebuggableRuleEngine::new();
984
985        engine.enable_debugging(true);
986        assert!(engine.debug_enabled);
987        assert!(engine.debug_session.step_mode);
988
989        engine.disable_debugging();
990        assert!(!engine.debug_enabled);
991    }
992
993    #[test]
994    fn test_breakpoint_management() {
995        let mut engine = DebuggableRuleEngine::new();
996
997        engine.add_breakpoint("test_rule");
998        assert!(engine.debug_session.breakpoints.contains("test_rule"));
999
1000        engine.remove_breakpoint("test_rule");
1001        assert!(!engine.debug_session.breakpoints.contains("test_rule"));
1002    }
1003
1004    #[test]
1005    fn test_trace_entry_recording() {
1006        let mut engine = DebuggableRuleEngine::new();
1007        engine.enable_debugging(false);
1008
1009        let entry = TraceEntry {
1010            timestamp: engine.current_timestamp(),
1011            rule_name: "test_rule".to_string(),
1012            action: TraceAction::RuleExecution,
1013            input_facts: vec![],
1014            output_facts: vec![],
1015            duration: Duration::from_millis(10),
1016            memory_usage: 1024,
1017        };
1018
1019        engine.record_trace_entry(entry);
1020        assert_eq!(engine.debug_session.trace.len(), 1);
1021        assert_eq!(
1022            engine
1023                .debug_session
1024                .metrics
1025                .rule_execution_counts
1026                .get("test_rule"),
1027            Some(&1)
1028        );
1029    }
1030
1031    #[test]
1032    fn test_performance_bottleneck_detection() {
1033        let mut engine = DebuggableRuleEngine::new();
1034        engine.enable_debugging(false);
1035
1036        // Add a slow rule execution
1037        engine
1038            .debug_session
1039            .metrics
1040            .rule_execution_times
1041            .insert("slow_rule".to_string(), Duration::from_millis(200));
1042
1043        engine.analyze_conflicts();
1044
1045        // Should detect performance bottleneck
1046        assert!(!engine.debug_session.conflicts.is_empty());
1047        assert!(engine
1048            .debug_session
1049            .conflicts
1050            .iter()
1051            .any(|c| { matches!(c.conflict_type, ConflictType::PerformanceBottleneck) }));
1052    }
1053
1054    #[test]
1055    fn test_debug_report_generation() {
1056        let mut engine = DebuggableRuleEngine::new();
1057        engine.enable_debugging(false);
1058
1059        // Add some test data
1060        engine.debug_session.metrics.facts_processed = 100;
1061        engine.debug_session.metrics.facts_derived = 50;
1062        engine.debug_session.metrics.total_execution_time = Duration::from_millis(500);
1063
1064        let report = engine.generate_debug_report();
1065        assert!(report.contains("RULE ENGINE DEBUG REPORT"));
1066        assert!(report.contains("Facts processed: 100"));
1067        assert!(report.contains("Facts derived: 50"));
1068    }
1069
1070    #[test]
1071    fn test_debug_data_export() -> Result<(), Box<dyn std::error::Error>> {
1072        let engine = DebuggableRuleEngine::new();
1073        let json_result = engine.export_debug_data();
1074        assert!(json_result.is_ok());
1075
1076        let json_data = json_result?;
1077        assert!(json_data.contains("trace"));
1078        assert!(json_data.contains("metrics"));
1079        assert!(json_data.contains("conflicts"));
1080        Ok(())
1081    }
1082
1083    #[test]
1084    fn test_conditional_breakpoint() {
1085        let mut engine = DebuggableRuleEngine::new();
1086        engine.enable_debugging(false);
1087
1088        // Add conditional breakpoint
1089        let condition = BreakpointCondition {
1090            variable: "X".to_string(),
1091            value: "test".to_string(),
1092            operator: ConditionOperator::Equals,
1093        };
1094        engine.add_conditional_breakpoint("test_rule", Some(condition), None);
1095
1096        // Set variable to meet condition
1097        engine.set_variable("X", "test");
1098
1099        // Should pause
1100        assert!(engine.should_pause("test_rule"));
1101
1102        // Different value should not pause
1103        engine.set_variable("X", "other");
1104        assert!(!engine.should_pause("test_rule"));
1105    }
1106
1107    #[test]
1108    fn test_hit_count_breakpoint() {
1109        let mut engine = DebuggableRuleEngine::new();
1110        engine.enable_debugging(false);
1111
1112        // Add breakpoint with hit count
1113        engine.add_conditional_breakpoint("count_rule", None, Some(3));
1114
1115        // Should pause first 3 times
1116        assert!(engine.should_pause("count_rule"));
1117        engine.increment_hit_count("count_rule");
1118        assert!(engine.should_pause("count_rule"));
1119        engine.increment_hit_count("count_rule");
1120        assert!(engine.should_pause("count_rule"));
1121        engine.increment_hit_count("count_rule");
1122
1123        // After 3 hits, should not pause
1124        assert!(!engine.should_pause("count_rule"));
1125    }
1126
1127    #[test]
1128    fn test_watch_expressions() {
1129        let mut engine = DebuggableRuleEngine::new();
1130        engine.enable_debugging(false);
1131
1132        engine.add_watch("x_watch", "X", true);
1133
1134        // Initial update
1135        let mut subs = HashMap::new();
1136        subs.insert("X".to_string(), "value1".to_string());
1137        engine.update_substitutions(subs);
1138
1139        // Check watch has value
1140        assert!(engine.debug_session.watch_expressions[0]
1141            .last_value
1142            .is_some());
1143
1144        // Update with new value - should trigger pause
1145        let mut subs2 = HashMap::new();
1146        subs2.insert("X".to_string(), "value2".to_string());
1147        engine.update_substitutions(subs2);
1148
1149        assert!(engine.is_paused());
1150        let events = engine.get_paused_events();
1151        assert!(!events.is_empty());
1152    }
1153
1154    #[test]
1155    fn test_call_stack() -> Result<(), Box<dyn std::error::Error>> {
1156        let mut engine = DebuggableRuleEngine::new();
1157        engine.enable_debugging(false);
1158
1159        // Push frames
1160        engine.push_frame("rule1", vec![]);
1161        engine.push_frame("rule2", vec![]);
1162        engine.push_frame("rule3", vec![]);
1163
1164        // Check stack depth
1165        assert_eq!(engine.get_call_stack().len(), 3);
1166
1167        // Pop frame
1168        let frame = engine.pop_frame();
1169        assert!(frame.is_some());
1170        assert_eq!(frame.ok_or("expected Some value")?.rule_name, "rule3");
1171
1172        // Check stack after pop
1173        assert_eq!(engine.get_call_stack().len(), 2);
1174        Ok(())
1175    }
1176
1177    #[test]
1178    fn test_debug_commands() {
1179        let mut engine = DebuggableRuleEngine::new();
1180        engine.enable_debugging(true);
1181
1182        // Test step command
1183        let result = engine.execute_command(DebugCommand::Step);
1184        assert!(result.contains("Stepping"));
1185        assert!(engine.debug_session.step_mode);
1186
1187        // Test continue command
1188        let result = engine.execute_command(DebugCommand::Continue);
1189        assert!(result.contains("Continuing"));
1190        assert!(!engine.debug_session.step_mode);
1191
1192        // Test quit command
1193        let result = engine.execute_command(DebugCommand::Quit);
1194        assert!(result.contains("Quitting"));
1195        assert_eq!(engine.get_state(), DebuggerState::Finished);
1196    }
1197
1198    #[test]
1199    fn test_format_backtrace() {
1200        let mut engine = DebuggableRuleEngine::new();
1201        engine.enable_debugging(false);
1202
1203        // Add some frames with substitutions
1204        engine.set_variable("X", "value1");
1205        engine.push_frame("rule1", vec![]);
1206        engine.set_variable("Y", "value2");
1207        engine.push_frame("rule2", vec![]);
1208
1209        let backtrace = engine.execute_command(DebugCommand::Backtrace);
1210        assert!(backtrace.contains("Call Stack"));
1211        assert!(backtrace.contains("rule1"));
1212        assert!(backtrace.contains("rule2"));
1213    }
1214
1215    #[test]
1216    fn test_breakpoint_enable_disable() {
1217        let mut engine = DebuggableRuleEngine::new();
1218        engine.enable_debugging(false);
1219
1220        engine.add_conditional_breakpoint("test_rule", None, None);
1221
1222        // Initially enabled
1223        assert!(engine.should_pause("test_rule"));
1224
1225        // Disable
1226        engine.set_breakpoint_enabled(0, false);
1227        assert!(!engine.should_pause("test_rule"));
1228
1229        // Re-enable
1230        engine.set_breakpoint_enabled(0, true);
1231        assert!(engine.should_pause("test_rule"));
1232    }
1233
1234    #[test]
1235    fn test_condition_operators() {
1236        let mut engine = DebuggableRuleEngine::new();
1237        engine.enable_debugging(false);
1238
1239        // Contains operator
1240        let condition = BreakpointCondition {
1241            variable: "X".to_string(),
1242            value: "sub".to_string(),
1243            operator: ConditionOperator::Contains,
1244        };
1245        engine.add_conditional_breakpoint("rule1", Some(condition), None);
1246
1247        engine.set_variable("X", "substring");
1248        assert!(engine.should_pause("rule1"));
1249
1250        // Not equals operator
1251        engine.debug_session.conditional_breakpoints.clear();
1252        let condition2 = BreakpointCondition {
1253            variable: "Y".to_string(),
1254            value: "excluded".to_string(),
1255            operator: ConditionOperator::NotEquals,
1256        };
1257        engine.add_conditional_breakpoint("rule2", Some(condition2), None);
1258
1259        engine.set_variable("Y", "included");
1260        assert!(engine.should_pause("rule2"));
1261
1262        engine.set_variable("Y", "excluded");
1263        assert!(!engine.should_pause("rule2"));
1264    }
1265
1266    #[test]
1267    fn test_step_out_command() {
1268        let mut engine = DebuggableRuleEngine::new();
1269        engine.enable_debugging(false);
1270
1271        // Push some frames
1272        engine.push_frame("rule1", vec![]);
1273        engine.push_frame("rule2", vec![]);
1274
1275        // Step out should pop frame
1276        let result = engine.execute_command(DebugCommand::StepOut);
1277        assert!(result.contains("Stepping out"));
1278        assert_eq!(engine.get_call_stack().len(), 1);
1279
1280        // Step out again
1281        engine.execute_command(DebugCommand::StepOut);
1282        assert_eq!(engine.get_call_stack().len(), 0);
1283
1284        // Step out with empty stack
1285        let result = engine.execute_command(DebugCommand::StepOut);
1286        assert!(result.contains("No frame"));
1287    }
1288}