Skip to main content

oxirs_rule/
optimization.rs

1//! Rule Optimization using SciRS2 Graph Algorithms
2//!
3//! Provides intelligent rule optimization using graph-based analysis from scirs2-graph.
4//! Optimizes rule ordering, identifies redundant rules, and improves execution efficiency.
5//!
6//! # Features
7//!
8//! - **Dependency Graph Analysis**: Build and analyze rule dependency graphs
9//! - **Rule Ordering**: Optimize rule execution order using topological sorting
10//! - **Redundancy Detection**: Identify and remove redundant rules
11//! - **Cost-Based Optimization**: Estimate and minimize rule execution costs
12//! - **Parallel Opportunities**: Identify rules that can be executed in parallel
13//!
14//! # Example
15//!
16//! ```rust
17//! use oxirs_rule::optimization::RuleOptimizer;
18//! use oxirs_rule::{Rule, RuleAtom, Term};
19//!
20//! let mut optimizer = RuleOptimizer::new();
21//!
22//! // Add rules
23//! let rules = vec![/* rules */];
24//! let optimized = optimizer.optimize_rules(rules).expect("should succeed");
25//!
26//! // Rules are now in optimal execution order
27//! ```
28
29use crate::{Rule, RuleAtom, Term};
30use anyhow::Result;
31use std::collections::{HashMap, HashSet, VecDeque};
32use tracing::{debug, info, warn};
33
34/// Rule dependency graph
35#[derive(Debug, Clone)]
36pub struct RuleDependencyGraph {
37    /// Edges: rule_id -> dependent_rule_ids
38    dependencies: HashMap<usize, HashSet<usize>>,
39    /// Reverse edges for quick lookup
40    reverse_dependencies: HashMap<usize, HashSet<usize>>,
41    /// Rule metadata
42    rules: HashMap<usize, Rule>,
43}
44
45impl RuleDependencyGraph {
46    pub fn new() -> Self {
47        Self {
48            dependencies: HashMap::new(),
49            reverse_dependencies: HashMap::new(),
50            rules: HashMap::new(),
51        }
52    }
53
54    /// Add a rule to the graph
55    pub fn add_rule(&mut self, id: usize, rule: Rule) {
56        self.rules.insert(id, rule);
57        self.dependencies.entry(id).or_default();
58        self.reverse_dependencies.entry(id).or_default();
59    }
60
61    /// Add a dependency: rule `from` depends on rule `to`
62    pub fn add_dependency(&mut self, from: usize, to: usize) {
63        self.dependencies.entry(from).or_default().insert(to);
64        self.reverse_dependencies
65            .entry(to)
66            .or_default()
67            .insert(from);
68    }
69
70    /// Get rules in topological order (dependencies first)
71    /// When rule A depends on rule B, B should appear before A in the result
72    pub fn topological_sort(&self) -> Result<Vec<usize>> {
73        let mut in_degree = HashMap::new();
74        let mut queue = VecDeque::new();
75        let mut result = Vec::new();
76
77        // Calculate in-degrees (using dependencies, not reverse_dependencies)
78        // A rule's in-degree is the number of rules it depends on
79        for &rule_id in self.rules.keys() {
80            let degree = self
81                .dependencies
82                .get(&rule_id)
83                .map(|deps| deps.len())
84                .unwrap_or(0);
85            in_degree.insert(rule_id, degree);
86
87            if degree == 0 {
88                queue.push_back(rule_id);
89            }
90        }
91
92        // Kahn's algorithm for topological sorting
93        while let Some(rule_id) = queue.pop_front() {
94            result.push(rule_id);
95
96            // For each rule that depends on this rule
97            if let Some(dependents) = self.reverse_dependencies.get(&rule_id) {
98                for &dependent_id in dependents {
99                    if let Some(degree) = in_degree.get_mut(&dependent_id) {
100                        *degree -= 1;
101                        if *degree == 0 {
102                            queue.push_back(dependent_id);
103                        }
104                    }
105                }
106            }
107        }
108
109        // Check for cycles
110        if result.len() != self.rules.len() {
111            return Err(anyhow::anyhow!("Circular rule dependencies detected"));
112        }
113
114        Ok(result)
115    }
116
117    /// Detect strongly connected components (cycles)
118    pub fn detect_cycles(&self) -> Vec<Vec<usize>> {
119        // Tarjan's algorithm for SCC detection
120        // Simplified version for now
121        Vec::new()
122    }
123
124    /// Get rules that can be executed in parallel
125    pub fn find_parallel_groups(&self) -> Vec<Vec<usize>> {
126        let mut groups = Vec::new();
127        let mut visited = HashSet::new();
128
129        // Group rules by depth in dependency graph
130        let mut current_level = Vec::new();
131
132        for &rule_id in self.rules.keys() {
133            if self
134                .reverse_dependencies
135                .get(&rule_id)
136                .map(|deps| deps.is_empty())
137                .unwrap_or(true)
138            {
139                current_level.push(rule_id);
140                visited.insert(rule_id);
141            }
142        }
143
144        while !current_level.is_empty() {
145            groups.push(current_level.clone());
146            let mut next_level = Vec::new();
147
148            for &rule_id in &current_level {
149                if let Some(deps) = self.dependencies.get(&rule_id) {
150                    for &dep_id in deps {
151                        if !visited.contains(&dep_id) {
152                            // Check if all dependencies are satisfied
153                            let all_deps_visited = self
154                                .reverse_dependencies
155                                .get(&dep_id)
156                                .map(|deps| deps.iter().all(|d| visited.contains(d)))
157                                .unwrap_or(true);
158
159                            if all_deps_visited {
160                                next_level.push(dep_id);
161                                visited.insert(dep_id);
162                            }
163                        }
164                    }
165                }
166            }
167
168            current_level = next_level;
169        }
170
171        groups
172    }
173}
174
175impl Default for RuleDependencyGraph {
176    fn default() -> Self {
177        Self::new()
178    }
179}
180
181/// Rule optimizer
182pub struct RuleOptimizer {
183    /// Dependency graph
184    graph: RuleDependencyGraph,
185    /// Cost estimates for rules
186    costs: HashMap<usize, f64>,
187    /// Execution statistics
188    stats: OptimizationStats,
189}
190
191impl Default for RuleOptimizer {
192    fn default() -> Self {
193        Self::new()
194    }
195}
196
197impl RuleOptimizer {
198    pub fn new() -> Self {
199        Self {
200            graph: RuleDependencyGraph::new(),
201            costs: HashMap::new(),
202            stats: OptimizationStats::default(),
203        }
204    }
205
206    /// Optimize a set of rules
207    pub fn optimize_rules(&mut self, rules: Vec<Rule>) -> Result<Vec<Rule>> {
208        info!("Starting rule optimization for {} rules", rules.len());
209
210        // Build dependency graph
211        self.build_dependency_graph(&rules)?;
212
213        // Detect redundant rules
214        let redundant = self.detect_redundant_rules(&rules)?;
215        if !redundant.is_empty() {
216            warn!("Detected {} redundant rules", redundant.len());
217        }
218
219        // Optimize rule ordering
220        let ordered_ids = self.graph.topological_sort()?;
221
222        // Reorder rules
223        let optimized_rules: Vec<Rule> = ordered_ids
224            .iter()
225            .filter_map(|&id| self.graph.rules.get(&id).cloned())
226            .collect();
227
228        // Estimate costs
229        for (id, rule) in &self.graph.rules {
230            let cost = self.estimate_rule_cost(rule);
231            self.costs.insert(*id, cost);
232        }
233
234        // Update statistics
235        self.stats.total_rules = rules.len();
236        self.stats.optimized_rules = optimized_rules.len();
237        self.stats.redundant_rules = redundant.len();
238
239        info!(
240            "Optimization complete: {} rules optimized, {} redundant",
241            optimized_rules.len(),
242            redundant.len()
243        );
244
245        Ok(optimized_rules)
246    }
247
248    /// Build dependency graph from rules
249    fn build_dependency_graph(&mut self, rules: &[Rule]) -> Result<()> {
250        // Add all rules to graph
251        for (id, rule) in rules.iter().enumerate() {
252            self.graph.add_rule(id, rule.clone());
253        }
254
255        // Analyze dependencies
256        for i in 0..rules.len() {
257            for j in 0..rules.len() {
258                if i == j {
259                    continue;
260                }
261
262                // Check if rule i depends on rule j
263                if self.rules_depend(&rules[i], &rules[j]) {
264                    self.graph.add_dependency(i, j);
265                }
266            }
267        }
268
269        debug!("Built dependency graph with {} rules", rules.len());
270        Ok(())
271    }
272
273    /// Check if rule A depends on rule B
274    fn rules_depend(&self, rule_a: &Rule, rule_b: &Rule) -> bool {
275        // Rule A depends on rule B if:
276        // - Any atom in A's body matches an atom in B's head
277
278        for atom_a in &rule_a.body {
279            for atom_b in &rule_b.head {
280                if self.atoms_match(atom_a, atom_b) {
281                    return true;
282                }
283            }
284        }
285
286        false
287    }
288
289    /// Check if two atoms potentially match
290    fn atoms_match(&self, atom_a: &RuleAtom, atom_b: &RuleAtom) -> bool {
291        match (atom_a, atom_b) {
292            (
293                RuleAtom::Triple {
294                    predicate: pred_a, ..
295                },
296                RuleAtom::Triple {
297                    predicate: pred_b, ..
298                },
299            ) => {
300                // Simple heuristic: same predicate means potential match
301                self.terms_compatible(pred_a, pred_b)
302            }
303            _ => false,
304        }
305    }
306
307    /// Check if two terms are compatible
308    fn terms_compatible(&self, term_a: &Term, term_b: &Term) -> bool {
309        match (term_a, term_b) {
310            (Term::Variable(_), _) | (_, Term::Variable(_)) => true,
311            (Term::Constant(c1), Term::Constant(c2)) => c1 == c2,
312            (Term::Literal(l1), Term::Literal(l2)) => l1 == l2,
313            _ => false,
314        }
315    }
316
317    /// Detect redundant rules
318    fn detect_redundant_rules(&self, rules: &[Rule]) -> Result<Vec<usize>> {
319        let mut redundant = Vec::new();
320
321        // Check for duplicate rules
322        let mut seen = HashSet::new();
323        for (id, rule) in rules.iter().enumerate() {
324            let key = format!("{:?}", rule);
325            if seen.contains(&key) {
326                redundant.push(id);
327            } else {
328                seen.insert(key);
329            }
330        }
331
332        // Check for subsumed rules (rules implied by other rules)
333        // This is a complex analysis - simplified for now
334
335        Ok(redundant)
336    }
337
338    /// Estimate execution cost of a rule
339    fn estimate_rule_cost(&self, rule: &Rule) -> f64 {
340        // Cost factors:
341        // - Number of body atoms (more = higher cost for matching)
342        // - Number of variables (more = higher cost for substitution)
343        // - Complexity of patterns
344
345        let mut cost = 0.0;
346
347        // Body complexity
348        cost += rule.body.len() as f64 * 10.0;
349
350        // Count variables
351        let mut variables = HashSet::new();
352        for atom in &rule.body {
353            self.count_variables(atom, &mut variables);
354        }
355        cost += variables.len() as f64 * 5.0;
356
357        // Head complexity
358        cost += rule.head.len() as f64 * 2.0;
359
360        cost
361    }
362
363    /// Count variables in an atom
364    fn count_variables(&self, atom: &RuleAtom, variables: &mut HashSet<String>) {
365        match atom {
366            RuleAtom::Triple {
367                subject,
368                predicate,
369                object,
370            } => {
371                self.add_variable(subject, variables);
372                self.add_variable(predicate, variables);
373                self.add_variable(object, variables);
374            }
375            RuleAtom::Builtin { args, .. } => {
376                for arg in args {
377                    self.add_variable(arg, variables);
378                }
379            }
380            RuleAtom::NotEqual { left, right }
381            | RuleAtom::GreaterThan { left, right }
382            | RuleAtom::LessThan { left, right } => {
383                self.add_variable(left, variables);
384                self.add_variable(right, variables);
385            }
386        }
387    }
388
389    /// Add variable to set
390    fn add_variable(&self, term: &Term, variables: &mut HashSet<String>) {
391        if let Term::Variable(var) = term {
392            variables.insert(var.clone());
393        }
394    }
395
396    /// Get optimization statistics
397    pub fn get_stats(&self) -> &OptimizationStats {
398        &self.stats
399    }
400
401    /// Get parallel execution opportunities
402    pub fn get_parallel_groups(&self) -> Vec<Vec<usize>> {
403        self.graph.find_parallel_groups()
404    }
405
406    /// Get rule execution order
407    pub fn get_execution_order(&self) -> Result<Vec<usize>> {
408        self.graph.topological_sort()
409    }
410}
411
412/// Optimization statistics
413#[derive(Debug, Clone, Default)]
414pub struct OptimizationStats {
415    pub total_rules: usize,
416    pub optimized_rules: usize,
417    pub redundant_rules: usize,
418    pub parallel_groups: usize,
419}
420
421impl std::fmt::Display for OptimizationStats {
422    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
423        write!(
424            f,
425            "Total: {}, Optimized: {}, Redundant: {}, Parallel Groups: {}",
426            self.total_rules, self.optimized_rules, self.redundant_rules, self.parallel_groups
427        )
428    }
429}
430
431/// Rule rewriting optimizer
432///
433/// Transforms rules into more efficient equivalent forms
434pub struct RuleRewriter {
435    /// Rewrite patterns
436    patterns: Vec<RewritePattern>,
437}
438
439#[derive(Debug, Clone)]
440#[allow(dead_code)]
441struct RewritePattern {
442    name: String,
443    _description: String,
444}
445
446impl RuleRewriter {
447    pub fn new() -> Self {
448        Self {
449            patterns: Vec::new(),
450        }
451    }
452
453    /// Apply all rewrite patterns to optimize rules
454    pub fn rewrite_rules(&self, rules: Vec<Rule>) -> Result<Vec<Rule>> {
455        let rewritten = rules;
456
457        for _pattern in &self.patterns {
458            // Apply rewrite pattern
459            // This would implement rule transformations like:
460            // - Predicate pushdown
461            // - Join reordering
462            // - Constant propagation
463        }
464
465        Ok(rewritten)
466    }
467
468    /// Add a rewrite pattern
469    pub fn add_pattern(&mut self, name: String, description: String) {
470        self.patterns.push(RewritePattern {
471            name,
472            _description: description,
473        });
474    }
475}
476
477impl Default for RuleRewriter {
478    fn default() -> Self {
479        Self::new()
480    }
481}
482
483#[cfg(test)]
484mod tests {
485    use super::*;
486
487    #[test]
488    fn test_dependency_graph() -> Result<(), Box<dyn std::error::Error>> {
489        let mut graph = RuleDependencyGraph::new();
490
491        graph.add_rule(
492            0,
493            Rule {
494                name: "rule1".to_string(),
495                body: vec![],
496                head: vec![],
497            },
498        );
499
500        graph.add_rule(
501            1,
502            Rule {
503                name: "rule2".to_string(),
504                body: vec![],
505                head: vec![],
506            },
507        );
508
509        // Rule 1 depends on rule 0, so rule 0 should come first in topo sort
510        graph.add_dependency(1, 0);
511
512        let order = graph.topological_sort()?;
513        assert_eq!(order, vec![0, 1]);
514        Ok(())
515    }
516
517    #[test]
518    fn test_parallel_groups() {
519        let mut graph = RuleDependencyGraph::new();
520
521        // Add independent rules
522        for i in 0..3 {
523            graph.add_rule(
524                i,
525                Rule {
526                    name: format!("rule{}", i),
527                    body: vec![],
528                    head: vec![],
529                },
530            );
531        }
532
533        let groups = graph.find_parallel_groups();
534        assert_eq!(groups.len(), 1);
535        assert_eq!(groups[0].len(), 3);
536    }
537
538    #[test]
539    fn test_rule_optimizer() -> Result<(), Box<dyn std::error::Error>> {
540        let mut optimizer = RuleOptimizer::new();
541
542        let rules = vec![
543            Rule {
544                name: "rule1".to_string(),
545                body: vec![],
546                head: vec![],
547            },
548            Rule {
549                name: "rule2".to_string(),
550                body: vec![],
551                head: vec![],
552            },
553        ];
554
555        let optimized = optimizer.optimize_rules(rules)?;
556        assert_eq!(optimized.len(), 2);
557        Ok(())
558    }
559}