Skip to main content

oxirs_rule/
materialization.rs

1//! Materialization Strategies for Rule-Based Reasoning
2//!
3//! Provides different strategies for materializing inferred knowledge:
4//! - **Eager**: Materialize all derivable facts immediately
5//! - **Lazy**: Materialize facts only when queried
6//! - **Semi-Eager**: Selectively materialize based on heuristics
7//!
8//! # Example
9//!
10//! ```rust
11//! use oxirs_rule::materialization::{MaterializationStrategy, EagerStrategy};
12//! use oxirs_rule::{Rule, RuleEngine};
13//!
14//! let mut engine = RuleEngine::new();
15//! let strategy = EagerStrategy::new();
16//!
17//! // Strategy will materialize all facts immediately
18//! ```
19
20use crate::{RuleAtom, RuleEngine};
21use anyhow::Result;
22use std::collections::{HashMap, HashSet};
23use tracing::{debug, info};
24
25/// Materialization strategy trait
26pub trait MaterializationStrategy: Send + Sync {
27    /// Materialize facts using this strategy
28    fn materialize(
29        &self,
30        engine: &mut RuleEngine,
31        initial_facts: &[RuleAtom],
32    ) -> Result<Vec<RuleAtom>>;
33
34    /// Get strategy name
35    fn name(&self) -> &str;
36
37    /// Get strategy description
38    fn description(&self) -> &str;
39}
40
41/// Eager materialization strategy
42///
43/// Computes all derivable facts immediately and stores them.
44/// Best for: Small knowledge bases, frequent queries, complete reasoning
45#[derive(Debug, Clone, Default)]
46pub struct EagerStrategy {
47    /// Maximum iterations for fixpoint computation
48    pub max_iterations: usize,
49}
50
51impl EagerStrategy {
52    pub fn new() -> Self {
53        Self {
54            max_iterations: 1000,
55        }
56    }
57
58    pub fn with_max_iterations(max_iterations: usize) -> Self {
59        Self { max_iterations }
60    }
61}
62
63impl MaterializationStrategy for EagerStrategy {
64    fn materialize(
65        &self,
66        engine: &mut RuleEngine,
67        initial_facts: &[RuleAtom],
68    ) -> Result<Vec<RuleAtom>> {
69        info!("Starting eager materialization");
70
71        // Add all initial facts
72        engine.add_facts(initial_facts.to_vec());
73
74        // Run forward chaining to fixpoint
75        let all_facts = engine.forward_chain(initial_facts)?;
76
77        info!("Eager materialization complete: {} facts", all_facts.len());
78        Ok(all_facts)
79    }
80
81    fn name(&self) -> &str {
82        "eager"
83    }
84
85    fn description(&self) -> &str {
86        "Materialize all derivable facts immediately"
87    }
88}
89
90/// Lazy materialization strategy
91///
92/// Computes facts only when they are queried.
93/// Best for: Large knowledge bases, infrequent queries, partial reasoning
94#[derive(Debug, Clone, Default)]
95pub struct LazyStrategy {
96    /// Cache of materialized facts
97    cache: HashMap<RuleAtom, bool>,
98}
99
100impl LazyStrategy {
101    pub fn new() -> Self {
102        Self {
103            cache: HashMap::new(),
104        }
105    }
106
107    /// Check if a specific fact can be derived
108    pub fn can_derive(&mut self, engine: &mut RuleEngine, target: &RuleAtom) -> Result<bool> {
109        // Check cache first
110        if let Some(&result) = self.cache.get(target) {
111            debug!("Cache hit for fact");
112            return Ok(result);
113        }
114
115        // Use backward chaining to check if target is derivable
116        let result = engine.backward_chain(target)?;
117
118        // Cache the result
119        self.cache.insert(target.clone(), result);
120
121        Ok(result)
122    }
123
124    /// Clear the cache
125    pub fn clear_cache(&mut self) {
126        self.cache.clear();
127    }
128}
129
130impl MaterializationStrategy for LazyStrategy {
131    fn materialize(
132        &self,
133        engine: &mut RuleEngine,
134        initial_facts: &[RuleAtom],
135    ) -> Result<Vec<RuleAtom>> {
136        info!("Lazy materialization: only storing initial facts");
137
138        // Only store initial facts, don't derive anything yet
139        engine.add_facts(initial_facts.to_vec());
140
141        Ok(initial_facts.to_vec())
142    }
143
144    fn name(&self) -> &str {
145        "lazy"
146    }
147
148    fn description(&self) -> &str {
149        "Materialize facts only when queried"
150    }
151}
152
153/// Semi-eager materialization strategy
154///
155/// Selectively materializes facts based on heuristics:
156/// - Materializes frequently used predicates
157/// - Materializes small derivation sets
158/// - Uses cost-based analysis
159///
160/// Best for: Medium knowledge bases, mixed query patterns
161#[derive(Debug, Clone)]
162pub struct SemiEagerStrategy {
163    /// Predicates to eagerly materialize
164    pub eager_predicates: HashSet<String>,
165    /// Maximum facts to materialize eagerly
166    pub max_eager_facts: usize,
167    /// Threshold for predicate frequency
168    pub frequency_threshold: usize,
169}
170
171impl Default for SemiEagerStrategy {
172    fn default() -> Self {
173        Self::new()
174    }
175}
176
177impl SemiEagerStrategy {
178    pub fn new() -> Self {
179        Self {
180            eager_predicates: HashSet::new(),
181            max_eager_facts: 10000,
182            frequency_threshold: 10,
183        }
184    }
185
186    pub fn with_eager_predicates(mut self, predicates: Vec<String>) -> Self {
187        self.eager_predicates = predicates.into_iter().collect();
188        self
189    }
190
191    pub fn with_max_eager_facts(mut self, max: usize) -> Self {
192        self.max_eager_facts = max;
193        self
194    }
195
196    /// Analyze predicates and decide which to materialize eagerly
197    fn analyze_predicates(&self, facts: &[RuleAtom]) -> HashSet<String> {
198        let mut predicate_counts = HashMap::new();
199
200        // Count predicate frequencies
201        for fact in facts {
202            if let RuleAtom::Triple {
203                predicate: crate::Term::Constant(pred),
204                ..
205            } = fact
206            {
207                *predicate_counts.entry(pred.clone()).or_insert(0) += 1;
208            }
209        }
210
211        // Select predicates above threshold
212        let mut selected = self.eager_predicates.clone();
213        for (pred, count) in predicate_counts {
214            if count >= self.frequency_threshold {
215                selected.insert(pred);
216            }
217        }
218
219        selected
220    }
221}
222
223impl MaterializationStrategy for SemiEagerStrategy {
224    fn materialize(
225        &self,
226        engine: &mut RuleEngine,
227        initial_facts: &[RuleAtom],
228    ) -> Result<Vec<RuleAtom>> {
229        info!("Starting semi-eager materialization");
230
231        // Add initial facts
232        engine.add_facts(initial_facts.to_vec());
233
234        // Analyze which predicates to materialize
235        let eager_preds = self.analyze_predicates(initial_facts);
236        debug!("Eagerly materializing {} predicates", eager_preds.len());
237
238        // Materialize facts for selected predicates
239        let all_facts = engine.forward_chain(initial_facts)?;
240
241        // Filter to keep only eagerly materialized predicates
242        let mut materialized = initial_facts.to_vec();
243        for fact in all_facts {
244            if materialized.len() >= self.max_eager_facts {
245                break;
246            }
247
248            if let RuleAtom::Triple {
249                predicate: crate::Term::Constant(pred),
250                ..
251            } = &fact
252            {
253                if eager_preds.contains(pred) {
254                    materialized.push(fact);
255                }
256            }
257        }
258
259        info!(
260            "Semi-eager materialization complete: {} facts materialized",
261            materialized.len()
262        );
263        Ok(materialized)
264    }
265
266    fn name(&self) -> &str {
267        "semi-eager"
268    }
269
270    fn description(&self) -> &str {
271        "Selectively materialize based on heuristics"
272    }
273}
274
275/// Adaptive materialization strategy
276///
277/// Dynamically switches between strategies based on workload characteristics.
278/// Uses machine learning-like heuristics to optimize performance.
279#[derive(Debug, Clone)]
280pub struct AdaptiveStrategy {
281    /// Current active strategy
282    current_strategy: StrategyType,
283    /// Query count since last adaptation
284    query_count: usize,
285    /// Threshold for switching strategies
286    adaptation_threshold: usize,
287    /// Performance metrics
288    metrics: PerformanceMetrics,
289}
290
291#[derive(Debug, Clone, Copy)]
292enum StrategyType {
293    Eager,
294    Lazy,
295    SemiEager,
296}
297
298#[derive(Debug, Clone, Default)]
299#[allow(dead_code)]
300struct PerformanceMetrics {
301    total_queries: usize,
302    cache_hits: usize,
303    materialization_time_ms: u128,
304    query_time_ms: u128,
305}
306
307impl Default for AdaptiveStrategy {
308    fn default() -> Self {
309        Self::new()
310    }
311}
312
313impl AdaptiveStrategy {
314    pub fn new() -> Self {
315        Self {
316            current_strategy: StrategyType::SemiEager,
317            query_count: 0,
318            adaptation_threshold: 100,
319            metrics: PerformanceMetrics::default(),
320        }
321    }
322
323    /// Analyze performance and adapt strategy
324    fn adapt(&mut self) {
325        let cache_hit_rate = if self.metrics.total_queries > 0 {
326            self.metrics.cache_hits as f64 / self.metrics.total_queries as f64
327        } else {
328            0.0
329        };
330
331        // Switch to eager if high cache hit rate
332        if cache_hit_rate > 0.8 {
333            debug!("Adapting to eager strategy (high cache hit rate)");
334            self.current_strategy = StrategyType::Eager;
335        }
336        // Switch to lazy if low cache hit rate
337        else if cache_hit_rate < 0.2 {
338            debug!("Adapting to lazy strategy (low cache hit rate)");
339            self.current_strategy = StrategyType::Lazy;
340        }
341        // Stay semi-eager otherwise
342        else {
343            self.current_strategy = StrategyType::SemiEager;
344        }
345
346        // Reset metrics
347        self.query_count = 0;
348    }
349
350    /// Record a query for adaptation
351    pub fn record_query(&mut self, cache_hit: bool) {
352        self.metrics.total_queries += 1;
353        if cache_hit {
354            self.metrics.cache_hits += 1;
355        }
356
357        self.query_count += 1;
358        if self.query_count >= self.adaptation_threshold {
359            self.adapt();
360        }
361    }
362}
363
364impl MaterializationStrategy for AdaptiveStrategy {
365    fn materialize(
366        &self,
367        engine: &mut RuleEngine,
368        initial_facts: &[RuleAtom],
369    ) -> Result<Vec<RuleAtom>> {
370        info!(
371            "Adaptive materialization using {:?} strategy",
372            self.current_strategy
373        );
374
375        match self.current_strategy {
376            StrategyType::Eager => EagerStrategy::new().materialize(engine, initial_facts),
377            StrategyType::Lazy => LazyStrategy::new().materialize(engine, initial_facts),
378            StrategyType::SemiEager => SemiEagerStrategy::new().materialize(engine, initial_facts),
379        }
380    }
381
382    fn name(&self) -> &str {
383        "adaptive"
384    }
385
386    fn description(&self) -> &str {
387        "Dynamically adapt strategy based on workload"
388    }
389}
390
391/// Materialization manager
392///
393/// Manages different materialization strategies and provides a unified interface
394pub struct MaterializationManager {
395    strategies: HashMap<String, Box<dyn MaterializationStrategy>>,
396    active_strategy: String,
397}
398
399impl MaterializationManager {
400    pub fn new() -> Self {
401        let mut manager = Self {
402            strategies: HashMap::new(),
403            active_strategy: String::from("semi-eager"),
404        };
405
406        // Register default strategies
407        manager.register_strategy(Box::new(EagerStrategy::new()));
408        manager.register_strategy(Box::new(LazyStrategy::new()));
409        manager.register_strategy(Box::new(SemiEagerStrategy::new()));
410        manager.register_strategy(Box::new(AdaptiveStrategy::new()));
411
412        manager
413    }
414
415    /// Register a materialization strategy
416    pub fn register_strategy(&mut self, strategy: Box<dyn MaterializationStrategy>) {
417        let name = strategy.name().to_string();
418        self.strategies.insert(name, strategy);
419    }
420
421    /// Set the active strategy
422    pub fn set_active_strategy(&mut self, name: &str) -> Result<()> {
423        if !self.strategies.contains_key(name) {
424            return Err(anyhow::anyhow!("Strategy '{}' not found", name));
425        }
426        self.active_strategy = name.to_string();
427        info!("Active materialization strategy set to '{}'", name);
428        Ok(())
429    }
430
431    /// Get the active strategy
432    pub fn get_active_strategy(&self) -> Option<&dyn MaterializationStrategy> {
433        self.strategies
434            .get(&self.active_strategy)
435            .map(|s| s.as_ref())
436    }
437
438    /// List available strategies
439    pub fn list_strategies(&self) -> Vec<(&str, &str)> {
440        self.strategies
441            .values()
442            .map(|s| (s.name(), s.description()))
443            .collect()
444    }
445
446    /// Materialize using the active strategy
447    pub fn materialize(
448        &self,
449        engine: &mut RuleEngine,
450        initial_facts: &[RuleAtom],
451    ) -> Result<Vec<RuleAtom>> {
452        let strategy = self
453            .get_active_strategy()
454            .ok_or_else(|| anyhow::anyhow!("No active strategy"))?;
455
456        info!("Materializing with {} strategy", strategy.name());
457        strategy.materialize(engine, initial_facts)
458    }
459}
460
461impl Default for MaterializationManager {
462    fn default() -> Self {
463        Self::new()
464    }
465}
466
467#[cfg(test)]
468mod tests {
469    use super::*;
470    use crate::Term;
471
472    #[test]
473    fn test_eager_strategy() -> Result<(), Box<dyn std::error::Error>> {
474        let mut engine = RuleEngine::new();
475        let strategy = EagerStrategy::new();
476
477        let facts = vec![RuleAtom::Triple {
478            subject: Term::Constant("a".to_string()),
479            predicate: Term::Constant("p".to_string()),
480            object: Term::Constant("b".to_string()),
481        }];
482
483        let result = strategy.materialize(&mut engine, &facts)?;
484        assert!(!result.is_empty());
485        Ok(())
486    }
487
488    #[test]
489    fn test_lazy_strategy() -> Result<(), Box<dyn std::error::Error>> {
490        let mut engine = RuleEngine::new();
491        let strategy = LazyStrategy::new();
492
493        let facts = vec![RuleAtom::Triple {
494            subject: Term::Constant("a".to_string()),
495            predicate: Term::Constant("p".to_string()),
496            object: Term::Constant("b".to_string()),
497        }];
498
499        let result = strategy.materialize(&mut engine, &facts)?;
500        // Lazy strategy only stores initial facts
501        assert_eq!(result.len(), facts.len());
502        Ok(())
503    }
504
505    #[test]
506    fn test_materialization_manager() -> Result<(), Box<dyn std::error::Error>> {
507        let mut manager = MaterializationManager::new();
508
509        // Check default strategies are registered
510        let strategies = manager.list_strategies();
511        assert!(strategies.len() >= 4);
512
513        // Set active strategy
514        manager.set_active_strategy("eager")?;
515        assert_eq!(manager.active_strategy, "eager");
516        Ok(())
517    }
518}