Skip to main content

oxirs_rule/
lazy_materialization.rs

1//! # Query-Driven Lazy Materialization Module
2//!
3//! This module provides on-demand materialization that only computes facts
4//! needed to answer specific queries, minimizing unnecessary computation and
5//! memory usage for large knowledge graphs.
6//!
7//! ## Features
8//!
9//! - **Query Pattern Analysis**: Analyzes queries to determine required inferences
10//! - **Selective Materialization**: Only materializes facts relevant to queries
11//! - **Dependency Tracking**: Tracks which rules can derive query patterns
12//! - **Incremental Computation**: Reuses previously materialized facts
13//! - **Cache Management**: Smart caching with eviction policies
14//! - **Performance Optimization**: Reduces memory footprint and computation time
15//!
16//! ## Example
17//!
18//! ```rust
19//! use oxirs_rule::lazy_materialization::*;
20//! use oxirs_rule::{Rule, RuleAtom, Term};
21//!
22//! // Create a lazy materializer
23//! let mut materializer = LazyMaterializer::new();
24//!
25//! // Add rules
26//! let rule = Rule {
27//!     name: "ancestor".to_string(),
28//!     body: vec![RuleAtom::Triple {
29//!         subject: Term::Variable("X".to_string()),
30//!         predicate: Term::Constant("parent".to_string()),
31//!         object: Term::Variable("Y".to_string()),
32//!     }],
33//!     head: vec![RuleAtom::Triple {
34//!         subject: Term::Variable("X".to_string()),
35//!         predicate: Term::Constant("ancestor".to_string()),
36//!         object: Term::Variable("Y".to_string()),
37//!     }],
38//! };
39//!
40//! materializer.add_rule(rule);
41//!
42//! // Add base facts
43//! let facts = vec![RuleAtom::Triple {
44//!     subject: Term::Constant("john".to_string()),
45//!     predicate: Term::Constant("parent".to_string()),
46//!     object: Term::Constant("mary".to_string()),
47//! }];
48//!
49//! materializer.add_facts(facts);
50//!
51//! // Query - only materializes what's needed
52//! let query = RuleAtom::Triple {
53//!     subject: Term::Constant("john".to_string()),
54//!     predicate: Term::Constant("ancestor".to_string()),
55//!     object: Term::Variable("Z".to_string()),
56//! };
57//!
58//! let results = materializer.query(&query).expect("should succeed");
59//! # Ok::<(), anyhow::Error>(())
60//! ```
61
62use crate::{Rule, RuleAtom, Term};
63use anyhow::Result;
64use std::collections::{HashMap, HashSet};
65
66/// Query pattern for matching against cached facts
67#[derive(Debug, Clone, PartialEq, Eq, Hash)]
68pub struct QueryPattern {
69    /// Predicate (None = wildcard)
70    pub predicate: Option<String>,
71    /// Subject type (constant, variable, any)
72    pub subject_type: PatternType,
73    /// Object type (constant, variable, any)
74    pub object_type: PatternType,
75}
76
77/// Type of term in a pattern
78#[derive(Debug, Clone, PartialEq, Eq, Hash)]
79pub enum PatternType {
80    Constant(String),
81    Variable,
82    Any,
83}
84
85impl QueryPattern {
86    /// Extract pattern from a query atom
87    pub fn from_atom(atom: &RuleAtom) -> Self {
88        match atom {
89            RuleAtom::Triple {
90                subject,
91                predicate,
92                object,
93            } => {
94                let pred = match predicate {
95                    Term::Constant(p) => Some(p.clone()),
96                    _ => None,
97                };
98
99                let subj_type = match subject {
100                    Term::Constant(s) => PatternType::Constant(s.clone()),
101                    Term::Variable(_) => PatternType::Variable,
102                    _ => PatternType::Any,
103                };
104
105                let obj_type = match object {
106                    Term::Constant(o) => PatternType::Constant(o.clone()),
107                    Term::Variable(_) => PatternType::Variable,
108                    _ => PatternType::Any,
109                };
110
111                QueryPattern {
112                    predicate: pred,
113                    subject_type: subj_type,
114                    object_type: obj_type,
115                }
116            }
117            _ => QueryPattern {
118                predicate: None,
119                subject_type: PatternType::Any,
120                object_type: PatternType::Any,
121            },
122        }
123    }
124
125    /// Check if this pattern matches an atom
126    pub fn matches(&self, atom: &RuleAtom) -> bool {
127        if let RuleAtom::Triple {
128            subject,
129            predicate,
130            object,
131        } = atom
132        {
133            // Check predicate
134            if let Some(ref p) = self.predicate {
135                if let Term::Constant(pred_val) = predicate {
136                    if p != pred_val {
137                        return false;
138                    }
139                } else {
140                    return false;
141                }
142            }
143
144            // Check subject type
145            match &self.subject_type {
146                PatternType::Constant(s) => {
147                    if let Term::Constant(subj_val) = subject {
148                        if s != subj_val {
149                            return false;
150                        }
151                    } else {
152                        return false;
153                    }
154                }
155                PatternType::Variable => {
156                    // Variable matches anything
157                }
158                PatternType::Any => {}
159            }
160
161            // Check object type
162            match &self.object_type {
163                PatternType::Constant(o) => {
164                    if let Term::Constant(obj_val) = object {
165                        if o != obj_val {
166                            return false;
167                        }
168                    } else {
169                        return false;
170                    }
171                }
172                PatternType::Variable => {
173                    // Variable matches anything
174                }
175                PatternType::Any => {}
176            }
177
178            true
179        } else {
180            false
181        }
182    }
183}
184
185/// Materialization cache entry
186#[derive(Debug, Clone)]
187struct CacheEntry {
188    /// Cached facts for this pattern
189    facts: Vec<RuleAtom>,
190    /// Timestamp of last materialization
191    timestamp: std::time::Instant,
192    /// Rules used to derive these facts
193    #[allow(dead_code)]
194    derived_by: HashSet<String>,
195}
196
197/// Query-driven lazy materializer
198pub struct LazyMaterializer {
199    /// Base facts (always available)
200    base_facts: Vec<RuleAtom>,
201    /// Rules for inference
202    rules: Vec<Rule>,
203    /// Cache of materialized facts by pattern
204    cache: HashMap<QueryPattern, CacheEntry>,
205    /// Index: predicate -> rules that can derive it
206    predicate_index: HashMap<String, Vec<usize>>,
207    /// Cache eviction policy
208    max_cache_size: usize,
209    /// Current cache size
210    cache_size: usize,
211    /// Cache statistics
212    cache_hits: usize,
213    cache_misses: usize,
214    query_count: usize,
215}
216
217impl LazyMaterializer {
218    /// Create a new lazy materializer
219    pub fn new() -> Self {
220        Self {
221            base_facts: Vec::new(),
222            rules: Vec::new(),
223            cache: HashMap::new(),
224            predicate_index: HashMap::new(),
225            max_cache_size: 10000,
226            cache_size: 0,
227            cache_hits: 0,
228            cache_misses: 0,
229            query_count: 0,
230        }
231    }
232
233    /// Create with custom cache size
234    pub fn with_cache_size(max_size: usize) -> Self {
235        let mut result = Self::new();
236        result.max_cache_size = max_size;
237        result
238    }
239
240    /// Add a rule to the materializer
241    pub fn add_rule(&mut self, rule: Rule) {
242        let rule_idx = self.rules.len();
243
244        // Index by predicates in head
245        for head_atom in &rule.head {
246            if let RuleAtom::Triple {
247                predicate: Term::Constant(pred),
248                ..
249            } = head_atom
250            {
251                self.predicate_index
252                    .entry(pred.clone())
253                    .or_default()
254                    .push(rule_idx);
255            }
256        }
257
258        self.rules.push(rule);
259    }
260
261    /// Add base facts
262    pub fn add_facts(&mut self, facts: Vec<RuleAtom>) {
263        self.base_facts.extend(facts);
264        // Invalidate cache when base facts change
265        self.invalidate_cache();
266    }
267
268    /// Query with lazy materialization
269    pub fn query(&mut self, query: &RuleAtom) -> Result<Vec<RuleAtom>> {
270        self.query_count += 1;
271
272        // Extract query pattern
273        let pattern = QueryPattern::from_atom(query);
274
275        // Check cache first
276        if let Some(entry) = self.cache.get(&pattern) {
277            self.cache_hits += 1;
278            // Filter cached facts by query
279            let results: Vec<_> = entry
280                .facts
281                .iter()
282                .filter(|fact| self.matches_query(query, fact))
283                .cloned()
284                .collect();
285            return Ok(results);
286        }
287
288        self.cache_misses += 1;
289
290        // Materialize on demand
291        let materialized = self.materialize_for_pattern(&pattern)?;
292
293        // Cache results
294        self.cache_materialized_facts(pattern, materialized.clone());
295
296        // Filter by specific query
297        let results: Vec<_> = materialized
298            .into_iter()
299            .filter(|fact| self.matches_query(query, fact))
300            .collect();
301
302        Ok(results)
303    }
304
305    /// Materialize facts for a specific pattern
306    fn materialize_for_pattern(&self, pattern: &QueryPattern) -> Result<Vec<RuleAtom>> {
307        let mut results = Vec::new();
308
309        // Start with ALL base facts (not just those matching pattern)
310        // because rule bodies might need facts with different predicates
311        let mut working_set = self.base_facts.clone();
312
313        // Find applicable rules
314        let applicable_rules = self.find_applicable_rules(pattern);
315
316        // Apply rules iteratively (fixed-point computation)
317        let mut changed = true;
318        let mut iterations = 0;
319        const MAX_ITERATIONS: usize = 100;
320
321        while changed && iterations < MAX_ITERATIONS {
322            changed = false;
323            iterations += 1;
324
325            for &rule_idx in &applicable_rules {
326                let rule = &self.rules[rule_idx];
327                let new_facts = self.apply_rule_to_facts(rule, &working_set);
328
329                for new_fact in new_facts {
330                    if !working_set.contains(&new_fact) {
331                        working_set.push(new_fact.clone());
332                        changed = true;
333                    }
334                }
335            }
336        }
337
338        // Filter results to match pattern
339        for fact in &working_set {
340            if pattern.matches(fact) {
341                results.push(fact.clone());
342            }
343        }
344
345        Ok(results)
346    }
347
348    /// Find rules that can derive facts matching the pattern
349    fn find_applicable_rules(&self, pattern: &QueryPattern) -> Vec<usize> {
350        if let Some(ref pred) = pattern.predicate {
351            // Use index to find rules that derive this predicate
352            self.predicate_index.get(pred).cloned().unwrap_or_default()
353        } else {
354            // No predicate specified - all rules might be applicable
355            (0..self.rules.len()).collect()
356        }
357    }
358
359    /// Apply a rule to a set of facts (simplified forward chaining)
360    fn apply_rule_to_facts(&self, rule: &Rule, facts: &[RuleAtom]) -> Vec<RuleAtom> {
361        let mut new_facts = Vec::new();
362
363        // Simple case: single atom in body
364        if rule.body.len() == 1 {
365            for fact in facts {
366                if let Some(substitution) = self.try_match(&rule.body[0], fact) {
367                    // Apply substitution to head
368                    for head_atom in &rule.head {
369                        if let Some(derived) = self.apply_substitution(head_atom, &substitution) {
370                            new_facts.push(derived);
371                        }
372                    }
373                }
374            }
375        }
376
377        new_facts
378    }
379
380    /// Try to match a rule atom against a fact
381    fn try_match(&self, pattern: &RuleAtom, fact: &RuleAtom) -> Option<HashMap<String, Term>> {
382        if let (
383            RuleAtom::Triple {
384                subject: ps,
385                predicate: pp,
386                object: po,
387            },
388            RuleAtom::Triple {
389                subject: fs,
390                predicate: fp,
391                object: fo,
392            },
393        ) = (pattern, fact)
394        {
395            let mut sub = HashMap::new();
396
397            // Match subject
398            if !self.unify_term(ps, fs, &mut sub) {
399                return None;
400            }
401
402            // Match predicate
403            if !self.unify_term(pp, fp, &mut sub) {
404                return None;
405            }
406
407            // Match object
408            if !self.unify_term(po, fo, &mut sub) {
409                return None;
410            }
411
412            Some(sub)
413        } else {
414            None
415        }
416    }
417
418    /// Simple unification for terms
419    fn unify_term(&self, pattern: &Term, fact: &Term, sub: &mut HashMap<String, Term>) -> bool {
420        match (pattern, fact) {
421            (Term::Variable(var), _) => {
422                if let Some(bound) = sub.get(var) {
423                    bound == fact
424                } else {
425                    sub.insert(var.clone(), fact.clone());
426                    true
427                }
428            }
429            (Term::Constant(p), Term::Constant(f)) => p == f,
430            _ => false,
431        }
432    }
433
434    /// Apply substitution to an atom
435    fn apply_substitution(&self, atom: &RuleAtom, sub: &HashMap<String, Term>) -> Option<RuleAtom> {
436        if let RuleAtom::Triple {
437            subject,
438            predicate,
439            object,
440        } = atom
441        {
442            let new_subj = self.substitute_term(subject, sub);
443            let new_pred = self.substitute_term(predicate, sub);
444            let new_obj = self.substitute_term(object, sub);
445
446            Some(RuleAtom::Triple {
447                subject: new_subj,
448                predicate: new_pred,
449                object: new_obj,
450            })
451        } else {
452            None
453        }
454    }
455
456    /// Substitute variables in a term
457    fn substitute_term(&self, term: &Term, sub: &HashMap<String, Term>) -> Term {
458        match term {
459            Term::Variable(var) => sub.get(var).cloned().unwrap_or_else(|| term.clone()),
460            _ => term.clone(),
461        }
462    }
463
464    /// Check if a fact matches a query
465    fn matches_query(&self, query: &RuleAtom, fact: &RuleAtom) -> bool {
466        if let (
467            RuleAtom::Triple {
468                subject: qs,
469                predicate: qp,
470                object: qo,
471            },
472            RuleAtom::Triple {
473                subject: fs,
474                predicate: fp,
475                object: fo,
476            },
477        ) = (query, fact)
478        {
479            self.term_matches(qs, fs) && self.term_matches(qp, fp) && self.term_matches(qo, fo)
480        } else {
481            false
482        }
483    }
484
485    /// Check if a query term matches a fact term
486    fn term_matches(&self, query_term: &Term, fact_term: &Term) -> bool {
487        match (query_term, fact_term) {
488            (Term::Variable(_), _) => true, // Variable matches anything
489            (Term::Constant(q), Term::Constant(f)) => q == f,
490            _ => false,
491        }
492    }
493
494    /// Cache materialized facts
495    fn cache_materialized_facts(&mut self, pattern: QueryPattern, facts: Vec<RuleAtom>) {
496        // Check cache size limit
497        if self.cache_size >= self.max_cache_size {
498            self.evict_cache_entry();
499        }
500
501        let entry = CacheEntry {
502            facts: facts.clone(),
503            timestamp: std::time::Instant::now(),
504            derived_by: HashSet::new(),
505        };
506
507        self.cache_size += facts.len();
508        self.cache.insert(pattern, entry);
509    }
510
511    /// Evict oldest cache entry (LRU policy)
512    fn evict_cache_entry(&mut self) {
513        if let Some((oldest_pattern, oldest_entry)) = self
514            .cache
515            .iter()
516            .min_by_key(|(_, entry)| entry.timestamp)
517            .map(|(p, e)| (p.clone(), e.clone()))
518        {
519            self.cache_size = self.cache_size.saturating_sub(oldest_entry.facts.len());
520            self.cache.remove(&oldest_pattern);
521        }
522    }
523
524    /// Invalidate entire cache
525    pub fn invalidate_cache(&mut self) {
526        self.cache.clear();
527        self.cache_size = 0;
528    }
529
530    /// Invalidate cache entries affected by a predicate
531    pub fn invalidate_predicate(&mut self, predicate: &str) {
532        let patterns_to_remove: Vec<_> = self
533            .cache
534            .keys()
535            .filter(|p| {
536                if let Some(ref pred) = p.predicate {
537                    pred == predicate
538                } else {
539                    false
540                }
541            })
542            .cloned()
543            .collect();
544
545        for pattern in patterns_to_remove {
546            if let Some(entry) = self.cache.remove(&pattern) {
547                self.cache_size = self.cache_size.saturating_sub(entry.facts.len());
548            }
549        }
550    }
551
552    /// Get cache statistics
553    pub fn cache_stats(&self) -> CacheStats {
554        CacheStats {
555            cache_size: self.cache_size,
556            num_patterns: self.cache.len(),
557            max_size: self.max_cache_size,
558            hit_rate: if self.cache_hits + self.cache_misses > 0 {
559                self.cache_hits as f64 / (self.cache_hits + self.cache_misses) as f64
560            } else {
561                0.0
562            },
563        }
564    }
565}
566
567impl Default for LazyMaterializer {
568    fn default() -> Self {
569        Self::new()
570    }
571}
572
573/// Cache statistics
574#[derive(Debug, Clone)]
575pub struct CacheStats {
576    pub cache_size: usize,
577    pub num_patterns: usize,
578    pub max_size: usize,
579    pub hit_rate: f64,
580}
581
582#[cfg(test)]
583mod tests {
584    use super::*;
585
586    fn create_simple_rule() -> Rule {
587        Rule {
588            name: "ancestor".to_string(),
589            body: vec![RuleAtom::Triple {
590                subject: Term::Variable("X".to_string()),
591                predicate: Term::Constant("parent".to_string()),
592                object: Term::Variable("Y".to_string()),
593            }],
594            head: vec![RuleAtom::Triple {
595                subject: Term::Variable("X".to_string()),
596                predicate: Term::Constant("ancestor".to_string()),
597                object: Term::Variable("Y".to_string()),
598            }],
599        }
600    }
601
602    #[test]
603    fn test_lazy_materializer_creation() {
604        let materializer = LazyMaterializer::new();
605        assert_eq!(materializer.rules.len(), 0);
606    }
607
608    #[test]
609    fn test_add_rule() {
610        let mut materializer = LazyMaterializer::new();
611        let rule = create_simple_rule();
612
613        materializer.add_rule(rule);
614
615        assert_eq!(materializer.rules.len(), 1);
616        assert!(materializer.predicate_index.contains_key("ancestor"));
617    }
618
619    #[test]
620    fn test_query_pattern_extraction() {
621        let atom = RuleAtom::Triple {
622            subject: Term::Constant("john".to_string()),
623            predicate: Term::Constant("parent".to_string()),
624            object: Term::Variable("X".to_string()),
625        };
626
627        let pattern = QueryPattern::from_atom(&atom);
628
629        assert_eq!(pattern.predicate, Some("parent".to_string()));
630        assert_eq!(
631            pattern.subject_type,
632            PatternType::Constant("john".to_string())
633        );
634        assert_eq!(pattern.object_type, PatternType::Variable);
635    }
636
637    #[test]
638    fn test_pattern_matching() {
639        let pattern = QueryPattern {
640            predicate: Some("parent".to_string()),
641            subject_type: PatternType::Variable,
642            object_type: PatternType::Variable,
643        };
644
645        let atom1 = RuleAtom::Triple {
646            subject: Term::Constant("john".to_string()),
647            predicate: Term::Constant("parent".to_string()),
648            object: Term::Constant("mary".to_string()),
649        };
650
651        let atom2 = RuleAtom::Triple {
652            subject: Term::Constant("john".to_string()),
653            predicate: Term::Constant("friend".to_string()),
654            object: Term::Constant("bob".to_string()),
655        };
656
657        assert!(pattern.matches(&atom1));
658        assert!(!pattern.matches(&atom2));
659    }
660
661    #[test]
662    fn test_lazy_query() -> Result<(), Box<dyn std::error::Error>> {
663        let mut materializer = LazyMaterializer::new();
664
665        // Add rule
666        materializer.add_rule(create_simple_rule());
667
668        // Add base facts
669        let facts = vec![RuleAtom::Triple {
670            subject: Term::Constant("john".to_string()),
671            predicate: Term::Constant("parent".to_string()),
672            object: Term::Constant("mary".to_string()),
673        }];
674
675        materializer.add_facts(facts);
676
677        // Query
678        let query = RuleAtom::Triple {
679            subject: Term::Constant("john".to_string()),
680            predicate: Term::Constant("ancestor".to_string()),
681            object: Term::Variable("Z".to_string()),
682        };
683
684        let results = materializer.query(&query)?;
685
686        // Should derive ancestor(john, mary) from parent(john, mary)
687        assert!(!results.is_empty());
688        Ok(())
689    }
690
691    #[test]
692    fn test_cache_hit() -> Result<(), Box<dyn std::error::Error>> {
693        let mut materializer = LazyMaterializer::new();
694
695        materializer.add_rule(create_simple_rule());
696
697        let facts = vec![RuleAtom::Triple {
698            subject: Term::Constant("john".to_string()),
699            predicate: Term::Constant("parent".to_string()),
700            object: Term::Constant("mary".to_string()),
701        }];
702
703        materializer.add_facts(facts);
704
705        let query = RuleAtom::Triple {
706            subject: Term::Variable("X".to_string()),
707            predicate: Term::Constant("ancestor".to_string()),
708            object: Term::Variable("Y".to_string()),
709        };
710
711        // First query - cache miss
712        let _results1 = materializer.query(&query)?;
713
714        // Second query - should hit cache
715        let _results2 = materializer.query(&query)?;
716
717        let stats = materializer.cache_stats();
718        assert!(stats.hit_rate > 0.0);
719        Ok(())
720    }
721
722    #[test]
723    fn test_cache_invalidation() -> Result<(), Box<dyn std::error::Error>> {
724        let mut materializer = LazyMaterializer::new();
725
726        materializer.add_rule(create_simple_rule());
727
728        let facts = vec![RuleAtom::Triple {
729            subject: Term::Constant("john".to_string()),
730            predicate: Term::Constant("parent".to_string()),
731            object: Term::Constant("mary".to_string()),
732        }];
733
734        materializer.add_facts(facts);
735
736        let query = RuleAtom::Triple {
737            subject: Term::Variable("X".to_string()),
738            predicate: Term::Constant("ancestor".to_string()),
739            object: Term::Variable("Y".to_string()),
740        };
741
742        // Query to populate cache
743        let _results = materializer.query(&query)?;
744
745        // Invalidate cache
746        materializer.invalidate_cache();
747
748        let stats = materializer.cache_stats();
749        assert_eq!(stats.cache_size, 0);
750        Ok(())
751    }
752
753    #[test]
754    fn test_predicate_invalidation() -> Result<(), Box<dyn std::error::Error>> {
755        let mut materializer = LazyMaterializer::new();
756
757        materializer.add_rule(create_simple_rule());
758
759        let facts = vec![RuleAtom::Triple {
760            subject: Term::Constant("john".to_string()),
761            predicate: Term::Constant("parent".to_string()),
762            object: Term::Constant("mary".to_string()),
763        }];
764
765        materializer.add_facts(facts);
766
767        let query = RuleAtom::Triple {
768            subject: Term::Variable("X".to_string()),
769            predicate: Term::Constant("ancestor".to_string()),
770            object: Term::Variable("Y".to_string()),
771        };
772
773        // Query to populate cache
774        let _results = materializer.query(&query)?;
775
776        // Invalidate specific predicate
777        materializer.invalidate_predicate("ancestor");
778
779        let stats = materializer.cache_stats();
780        assert_eq!(stats.cache_size, 0);
781        Ok(())
782    }
783
784    #[test]
785    fn test_cache_eviction() {
786        let mut materializer = LazyMaterializer::with_cache_size(10);
787
788        materializer.add_rule(create_simple_rule());
789
790        // Add enough facts to trigger eviction
791        for i in 0..15 {
792            let facts = vec![RuleAtom::Triple {
793                subject: Term::Constant(format!("entity_{}", i)),
794                predicate: Term::Constant("parent".to_string()),
795                object: Term::Constant(format!("entity_{}", i + 100)),
796            }];
797
798            materializer.add_facts(facts);
799
800            let query = RuleAtom::Triple {
801                subject: Term::Constant(format!("entity_{}", i)),
802                predicate: Term::Constant("ancestor".to_string()),
803                object: Term::Variable("Y".to_string()),
804            };
805
806            let _ = materializer.query(&query);
807        }
808
809        let stats = materializer.cache_stats();
810        assert!(stats.cache_size <= 10);
811    }
812}