Skip to main content

oxirs_rule/
advanced_integration_example.rs

1//! Advanced Integration Example
2//!
3//! Demonstrates all Beta.1 features working together in a realistic scenario:
4//! - Rule Composition (modules, templates, inheritance)
5//! - Custom Rule Language (DSL)
6//! - SPARQL Integration (query-driven reasoning)
7//! - SHACL Integration (validation with reasoning)
8//! - Distributed Reasoning (scaling)
9//! - Explanation Support
10//! - Conflict Resolution
11//! - Transactions
12//!
13//! # Scenario: E-Commerce Knowledge Graph
14//!
15//! This example implements a complete e-commerce knowledge graph with:
16//! - Product recommendations based on rules
17//! - Inventory validation with SHACL
18//! - Distributed query processing
19//! - Transaction support for order processing
20//! - Explanation of recommendations
21
22use crate::{
23    composition::{CompositionManager, RuleModule},
24    conflict::{ConflictResolver, Priority},
25    distributed::{DistributedReasoner, Node, PartitionStrategy},
26    explanation::ExplanationEngine,
27    shacl_integration::{ShaclRuleIntegration, ShapeConstraint, ValidationMode},
28    sparql_integration::{QueryMode, QueryPattern, SparqlRuleIntegration},
29    transaction::{IsolationLevel, TransactionManager},
30    Rule, RuleAtom, RuleEngine, Term,
31};
32use anyhow::Result;
33use tracing::{debug, info};
34
35/// E-Commerce reasoning system with all Beta.1 features
36pub struct EcommerceReasoningSystem {
37    /// Main rule engine
38    engine: RuleEngine,
39    /// Composition manager for rule organization
40    composition: CompositionManager,
41    /// SPARQL integration for query-driven reasoning
42    sparql: SparqlRuleIntegration,
43    /// SHACL integration for validation
44    shacl: ShaclRuleIntegration,
45    /// Distributed reasoner for scaling
46    distributed: DistributedReasoner,
47    /// Explanation engine for provenance
48    explanation: ExplanationEngine,
49    /// Conflict resolver for rule priorities
50    conflict: ConflictResolver,
51    /// Transaction manager for ACID operations
52    transactions: TransactionManager,
53}
54
55impl EcommerceReasoningSystem {
56    /// Create a new e-commerce reasoning system
57    pub fn new() -> Self {
58        info!("Initializing E-Commerce Reasoning System with all Beta.1 features");
59
60        let engine = RuleEngine::new();
61        let composition = CompositionManager::new();
62        let sparql = SparqlRuleIntegration::new(RuleEngine::new());
63        let shacl = ShaclRuleIntegration::new(RuleEngine::new());
64        let distributed = DistributedReasoner::new(PartitionStrategy::LoadBalanced);
65        let explanation = ExplanationEngine::new();
66        let conflict = ConflictResolver::new();
67        let transactions = TransactionManager::new();
68
69        Self {
70            engine,
71            composition,
72            sparql,
73            shacl,
74            distributed,
75            explanation,
76            conflict,
77            transactions,
78        }
79    }
80
81    /// Initialize the system with product recommendation rules
82    pub fn initialize_product_rules(&mut self) -> Result<()> {
83        info!("Initializing product recommendation rules");
84
85        // Create a rule module for product recommendations
86        let mut product_module = RuleModule::new("product_recommendations".to_string());
87        product_module.set_description("Rules for product recommendations".to_string());
88
89        // Add rule: customers who bought X also bought Y
90        let also_bought_rule = Rule {
91            name: "also_bought".to_string(),
92            body: vec![
93                RuleAtom::Triple {
94                    subject: Term::Variable("customer1".to_string()),
95                    predicate: Term::Constant("purchased".to_string()),
96                    object: Term::Variable("product1".to_string()),
97                },
98                RuleAtom::Triple {
99                    subject: Term::Variable("customer2".to_string()),
100                    predicate: Term::Constant("purchased".to_string()),
101                    object: Term::Variable("product1".to_string()),
102                },
103                RuleAtom::Triple {
104                    subject: Term::Variable("customer2".to_string()),
105                    predicate: Term::Constant("purchased".to_string()),
106                    object: Term::Variable("product2".to_string()),
107                },
108                RuleAtom::NotEqual {
109                    left: Term::Variable("customer1".to_string()),
110                    right: Term::Variable("customer2".to_string()),
111                },
112                RuleAtom::NotEqual {
113                    left: Term::Variable("product1".to_string()),
114                    right: Term::Variable("product2".to_string()),
115                },
116            ],
117            head: vec![RuleAtom::Triple {
118                subject: Term::Variable("customer1".to_string()),
119                predicate: Term::Constant("recommended".to_string()),
120                object: Term::Variable("product2".to_string()),
121            }],
122        };
123
124        product_module.add_rule(also_bought_rule);
125
126        // Set high priority for recommendation rules
127        self.conflict.set_priority("also_bought", Priority::High);
128
129        // Register the module
130        self.composition.register_module(product_module)?;
131
132        Ok(())
133    }
134
135    /// Initialize inventory validation rules using SHACL
136    pub fn initialize_inventory_validation(&mut self) -> Result<()> {
137        info!("Initializing inventory validation with SHACL");
138
139        // Create SHACL constraints for inventory
140        let _min_stock_constraint =
141            ShapeConstraint::new("min_stock".to_string(), "sh:minCount".to_string());
142
143        // Create repair rule for low stock
144        let low_stock_repair = Rule {
145            name: "reorder_low_stock".to_string(),
146            body: vec![
147                RuleAtom::Triple {
148                    subject: Term::Variable("product".to_string()),
149                    predicate: Term::Constant("stock".to_string()),
150                    object: Term::Variable("quantity".to_string()),
151                },
152                RuleAtom::LessThan {
153                    left: Term::Variable("quantity".to_string()),
154                    right: Term::Literal("10".to_string()),
155                },
156            ],
157            head: vec![RuleAtom::Triple {
158                subject: Term::Variable("product".to_string()),
159                predicate: Term::Constant("needsReorder".to_string()),
160                object: Term::Constant("true".to_string()),
161            }],
162        };
163
164        self.shacl
165            .register_repair_rule("sh:minCount".to_string(), low_stock_repair);
166        self.shacl.set_mode(ValidationMode::Full);
167
168        Ok(())
169    }
170
171    /// Setup distributed reasoning with multiple nodes
172    pub fn setup_distributed_reasoning(&mut self) -> Result<()> {
173        info!("Setting up distributed reasoning infrastructure");
174
175        // Register reasoning nodes
176        let node1 =
177            Node::new("node1".to_string(), "localhost:8001".to_string()).with_capacity(1000);
178        let node2 =
179            Node::new("node2".to_string(), "localhost:8002".to_string()).with_capacity(1500);
180        let node3 =
181            Node::new("node3".to_string(), "localhost:8003".to_string()).with_capacity(2000);
182
183        self.distributed.register_node(node1)?;
184        self.distributed.register_node(node2)?;
185        self.distributed.register_node(node3)?;
186
187        info!(
188            "Registered {} reasoning nodes",
189            self.distributed.node_count()
190        );
191
192        Ok(())
193    }
194
195    /// Process customer order with full transaction support
196    pub fn process_order(&mut self, customer: &str, product: &str) -> Result<()> {
197        info!(
198            "Processing order for customer '{}' - product '{}'",
199            customer, product
200        );
201
202        // Begin transaction
203        let tx_id = self
204            .transactions
205            .begin_transaction(IsolationLevel::Serializable)?;
206        debug!("Started transaction {}", tx_id);
207
208        // Add purchase fact
209        let purchase_fact = RuleAtom::Triple {
210            subject: Term::Constant(customer.to_string()),
211            predicate: Term::Constant("purchased".to_string()),
212            object: Term::Constant(product.to_string()),
213        };
214
215        self.transactions.add_fact(tx_id, purchase_fact.clone())?;
216
217        // Record explanation
218        self.explanation.record_assertion(purchase_fact.clone());
219
220        // Apply recommendation rules
221        let derived = self.engine.forward_chain(&[purchase_fact])?;
222        debug!("Derived {} recommendations", derived.len());
223
224        // Commit transaction
225        self.transactions.commit(tx_id)?;
226        info!("Order processed successfully");
227
228        Ok(())
229    }
230
231    /// Query recommendations using SPARQL integration
232    pub fn query_recommendations(&mut self, customer: &str) -> Result<Vec<String>> {
233        info!("Querying recommendations for customer '{}'", customer);
234
235        // Set query mode to hybrid (forward + backward)
236        self.sparql.engine_mut().add_facts(self.engine.get_facts());
237        self.sparql.set_mode(QueryMode::Hybrid);
238
239        // Create query pattern for recommendations
240        let pattern = QueryPattern::new(
241            Some(customer.to_string()),
242            Some("recommended".to_string()),
243            None, // Match any product
244        );
245
246        let results = self.sparql.query_with_reasoning(&[pattern])?;
247
248        // Extract product names
249        let products: Vec<String> = results
250            .iter()
251            .filter_map(|atom| {
252                if let RuleAtom::Triple {
253                    object: Term::Constant(product),
254                    ..
255                } = atom
256                {
257                    Some(product.clone())
258                } else {
259                    None
260                }
261            })
262            .collect();
263
264        info!("Found {} recommendations", products.len());
265        Ok(products)
266    }
267
268    /// Validate inventory using SHACL
269    pub fn validate_inventory(&mut self, inventory_facts: &[RuleAtom]) -> Result<bool> {
270        info!("Validating inventory with {} facts", inventory_facts.len());
271
272        let constraint =
273            ShapeConstraint::new("inventory_check".to_string(), "sh:minCount".to_string());
274
275        let report = self
276            .shacl
277            .validate_with_reasoning(&[constraint], inventory_facts)?;
278
279        if !report.conforms {
280            info!(
281                "Validation failed: {} violations, {} warnings",
282                report.violation_count(),
283                report.warning_count()
284            );
285        } else {
286            info!("Validation passed");
287        }
288
289        Ok(report.conforms)
290    }
291
292    /// Execute distributed reasoning for large datasets
293    pub fn execute_distributed(&mut self, facts: &[RuleAtom]) -> Result<Vec<RuleAtom>> {
294        info!(
295            "Executing distributed reasoning across {} nodes",
296            self.distributed.node_count()
297        );
298
299        let rules = self.composition.get_all_rules();
300        let results = self.distributed.execute_distributed(&rules, facts)?;
301
302        info!(
303            "Distributed execution complete: {} facts derived",
304            results.len()
305        );
306        Ok(results)
307    }
308
309    /// Get explanation for a recommendation
310    pub fn explain_recommendation(&self, customer: &str, product: &str) -> Result<String> {
311        let fact = RuleAtom::Triple {
312            subject: Term::Constant(customer.to_string()),
313            predicate: Term::Constant("recommended".to_string()),
314            object: Term::Constant(product.to_string()),
315        };
316
317        let explanation = self.explanation.explain_why(&fact)?;
318        Ok(format!("{}", explanation))
319    }
320
321    /// Get comprehensive statistics
322    pub fn get_statistics(&self) -> SystemStatistics {
323        SystemStatistics {
324            total_rules: self.composition.get_all_rules().len(),
325            total_modules: self.composition.get_stats().total_modules,
326            total_nodes: self.distributed.node_count(),
327            sparql_queries: self.sparql.get_stats().total_queries,
328            shacl_validations: self.shacl.get_stats().total_validations,
329            transactions: self.transactions.get_stats().total_transactions,
330            explanations: self.explanation.get_stats().total_derivations,
331        }
332    }
333}
334
335impl Default for EcommerceReasoningSystem {
336    fn default() -> Self {
337        Self::new()
338    }
339}
340
341/// System statistics
342#[derive(Debug, Clone)]
343pub struct SystemStatistics {
344    pub total_rules: usize,
345    pub total_modules: usize,
346    pub total_nodes: usize,
347    pub sparql_queries: usize,
348    pub shacl_validations: usize,
349    pub transactions: usize,
350    pub explanations: usize,
351}
352
353impl std::fmt::Display for SystemStatistics {
354    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
355        writeln!(f, "E-Commerce Reasoning System Statistics:")?;
356        writeln!(f, "  Rules: {}", self.total_rules)?;
357        writeln!(f, "  Modules: {}", self.total_modules)?;
358        writeln!(f, "  Distributed Nodes: {}", self.total_nodes)?;
359        writeln!(f, "  SPARQL Queries: {}", self.sparql_queries)?;
360        writeln!(f, "  SHACL Validations: {}", self.shacl_validations)?;
361        writeln!(f, "  Transactions: {}", self.transactions)?;
362        writeln!(f, "  Explanations Generated: {}", self.explanations)?;
363        Ok(())
364    }
365}
366
367#[cfg(test)]
368mod tests {
369    use super::*;
370
371    #[test]
372    fn test_ecommerce_system_creation() {
373        let system = EcommerceReasoningSystem::new();
374        assert_eq!(system.distributed.node_count(), 0);
375    }
376
377    #[test]
378    fn test_initialize_product_rules() -> Result<(), Box<dyn std::error::Error>> {
379        let mut system = EcommerceReasoningSystem::new();
380        system.initialize_product_rules()?;
381
382        let stats = system.get_statistics();
383        assert!(stats.total_modules > 0);
384        Ok(())
385    }
386
387    #[test]
388    fn test_setup_distributed_reasoning() -> Result<(), Box<dyn std::error::Error>> {
389        let mut system = EcommerceReasoningSystem::new();
390        system.setup_distributed_reasoning()?;
391
392        assert_eq!(system.distributed.node_count(), 3);
393        Ok(())
394    }
395
396    #[test]
397    fn test_process_order() -> Result<(), Box<dyn std::error::Error>> {
398        let mut system = EcommerceReasoningSystem::new();
399        system.initialize_product_rules()?;
400
401        let result = system.process_order("customer1", "product1");
402        assert!(result.is_ok());
403
404        let stats = system.get_statistics();
405        assert!(stats.transactions > 0);
406        Ok(())
407    }
408
409    #[test]
410    fn test_validate_inventory() -> Result<(), Box<dyn std::error::Error>> {
411        let mut system = EcommerceReasoningSystem::new();
412        system.initialize_inventory_validation()?;
413
414        let inventory_facts = vec![RuleAtom::Triple {
415            subject: Term::Constant("product1".to_string()),
416            predicate: Term::Constant("stock".to_string()),
417            object: Term::Literal("100".to_string()),
418        }];
419
420        let valid = system.validate_inventory(&inventory_facts)?;
421        assert!(valid);
422        Ok(())
423    }
424
425    #[test]
426    fn test_full_integration_workflow() -> Result<(), Box<dyn std::error::Error>> {
427        let mut system = EcommerceReasoningSystem::new();
428
429        // Initialize all components
430        system.initialize_product_rules()?;
431        system.initialize_inventory_validation()?;
432        system.setup_distributed_reasoning()?;
433
434        // Process some orders
435        system.process_order("alice", "laptop")?;
436        system.process_order("bob", "laptop")?;
437        system.process_order("bob", "mouse")?;
438
439        // Query recommendations (alice should get mouse recommended)
440        let recommendations = system.query_recommendations("alice").unwrap_or_default();
441
442        // Get statistics
443        let stats = system.get_statistics();
444        assert!(stats.total_modules > 0);
445        assert!(stats.total_nodes == 3);
446
447        println!("\n{}", stats);
448        println!("Recommendations for alice: {:?}", recommendations);
449        Ok(())
450    }
451
452    #[test]
453    fn test_statistics_display() {
454        let system = EcommerceReasoningSystem::new();
455        let stats = system.get_statistics();
456
457        let display = format!("{}", stats);
458        assert!(display.contains("E-Commerce Reasoning System Statistics"));
459    }
460}