1use crate::{Rule, RuleAtom, Term};
39use anyhow::Result;
40use once_cell::sync::Lazy;
41use scirs2_core::metrics::Counter;
42use std::collections::{HashMap, HashSet};
43use std::sync::{Arc, Mutex};
44use tracing::{debug, info};
45
46static PARALLEL_SUBSTITUTION_CLONES: Lazy<Counter> =
48 Lazy::new(|| Counter::new("parallel_substitution_clones".to_string()));
49static PARALLEL_RULE_APPLICATIONS: Lazy<Counter> =
50 Lazy::new(|| Counter::new("parallel_rule_applications".to_string()));
51
52#[derive(Debug)]
54pub struct ParallelEngine {
55 rules: Vec<Rule>,
57 facts: Arc<Mutex<HashSet<RuleAtom>>>,
59 num_threads: usize,
61 batch_size: usize,
63 simd_enabled: bool,
65}
66
67impl Default for ParallelEngine {
68 fn default() -> Self {
69 Self::new()
70 }
71}
72
73impl ParallelEngine {
74 pub fn new() -> Self {
76 let num_threads = std::thread::available_parallelism()
77 .map(|n| n.get())
78 .unwrap_or(4);
79
80 Self {
81 rules: Vec::new(),
82 facts: Arc::new(Mutex::new(HashSet::new())),
83 num_threads,
84 batch_size: 1000,
85 simd_enabled: true,
86 }
87 }
88
89 pub fn with_config(num_threads: usize, batch_size: usize) -> Self {
91 Self {
92 rules: Vec::new(),
93 facts: Arc::new(Mutex::new(HashSet::new())),
94 num_threads,
95 batch_size,
96 simd_enabled: true,
97 }
98 }
99
100 pub fn add_rule(&mut self, rule: Rule) {
102 self.rules.push(rule);
103 }
104
105 pub fn add_facts(&self, facts: Vec<RuleAtom>) {
107 let mut fact_set = self.facts.lock().expect("lock should not be poisoned");
108 fact_set.extend(facts);
109 }
110
111 pub fn execute_parallel(&self, initial_facts: &[RuleAtom]) -> Result<Vec<RuleAtom>> {
113 info!(
114 "Starting parallel execution with {} threads",
115 self.num_threads
116 );
117
118 {
120 let mut fact_set = self.facts.lock().expect("lock should not be poisoned");
121 fact_set.clear();
122 fact_set.extend(initial_facts.iter().cloned());
123 }
124
125 let mut iteration = 0;
126 let mut new_facts_added = true;
127
128 while new_facts_added {
129 iteration += 1;
130
131 debug!("Parallel iteration {}", iteration);
132
133 let derived = self.process_rules_parallel()?;
135
136 let mut fact_set = self.facts.lock().expect("lock should not be poisoned");
138 let initial_size = fact_set.len();
139
140 for fact in derived {
141 fact_set.insert(fact);
142 }
143
144 new_facts_added = fact_set.len() > initial_size;
145
146 if iteration > 100 {
148 break;
149 }
150 }
151
152 let fact_set = self.facts.lock().expect("lock should not be poisoned");
153 let result = fact_set.iter().cloned().collect();
154
155 info!(
156 "Parallel execution completed after {} iterations",
157 iteration
158 );
159 Ok(result)
160 }
161
162 fn process_rules_parallel(&self) -> Result<Vec<RuleAtom>> {
164 let mut all_derived = Vec::new();
165
166 let rules_per_thread = (self.rules.len() + self.num_threads - 1) / self.num_threads;
170
171 let mut handles = Vec::new();
172
173 for thread_id in 0..self.num_threads {
174 let start = thread_id * rules_per_thread;
175 let end = ((thread_id + 1) * rules_per_thread).min(self.rules.len());
176
177 if start >= end {
178 continue;
179 }
180
181 let rules_chunk: Vec<Rule> = self.rules[start..end].to_vec();
182 let facts = Arc::clone(&self.facts);
183
184 let handle = std::thread::spawn(move || {
185 let mut thread_derived = Vec::new();
186 let fact_set = facts.lock().expect("lock should not be poisoned");
187
188 for rule in &rules_chunk {
189 if let Ok(derived) = Self::apply_rule_to_facts(rule, &fact_set) {
191 thread_derived.extend(derived);
192 }
193 }
194
195 thread_derived
196 });
197
198 handles.push(handle);
199 }
200
201 for handle in handles {
203 let thread_derived = handle
204 .join()
205 .map_err(|_| anyhow::anyhow!("Thread panicked during rule execution"))?;
206 all_derived.extend(thread_derived);
207 }
208
209 Ok(all_derived)
210 }
211
212 fn apply_rule_to_facts(rule: &Rule, facts: &HashSet<RuleAtom>) -> Result<Vec<RuleAtom>> {
214 let mut derived = Vec::new();
215
216 PARALLEL_RULE_APPLICATIONS.inc();
218
219 let substitutions = Self::find_substitutions(&rule.body, facts)?;
221
222 for substitution in substitutions {
224 for head_atom in &rule.head {
225 let instantiated = Self::apply_substitution(head_atom, &substitution);
226 derived.push(instantiated);
227 }
228 }
229
230 Ok(derived)
231 }
232
233 fn find_substitutions(
235 body: &[RuleAtom],
236 facts: &HashSet<RuleAtom>,
237 ) -> Result<Vec<HashMap<String, Term>>> {
238 if body.is_empty() {
239 return Ok(vec![HashMap::new()]);
240 }
241
242 let mut substitutions = Self::match_atom(&body[0], facts, &HashMap::new())?;
243
244 for atom in &body[1..] {
245 let mut new_subs = Vec::new();
246 for sub in substitutions {
247 let extended = Self::match_atom(atom, facts, &sub)?;
248 new_subs.extend(extended);
249 }
250 substitutions = new_subs;
251 }
252
253 Ok(substitutions)
254 }
255
256 fn match_atom(
259 atom: &RuleAtom,
260 facts: &HashSet<RuleAtom>,
261 partial_sub: &HashMap<String, Term>,
262 ) -> Result<Vec<HashMap<String, Term>>> {
263 let mut substitutions = Vec::new();
264
265 if let RuleAtom::Triple {
266 subject,
267 predicate,
268 object,
269 } = atom
270 {
271 for fact in facts {
272 if let RuleAtom::Triple {
273 subject: fs,
274 predicate: fp,
275 object: fo,
276 } = fact
277 {
278 if let Some(sub) = Self::unify_triple(
280 (subject, predicate, object),
281 (fs, fp, fo),
282 partial_sub, ) {
284 substitutions.push(sub);
285 }
286 }
287 }
288 }
289
290 Ok(substitutions)
291 }
292
293 fn unify_triple(
296 pattern: (&Term, &Term, &Term),
297 fact: (&Term, &Term, &Term),
298 substitution: &HashMap<String, Term>,
299 ) -> Option<HashMap<String, Term>> {
300 let mut new_substitution = substitution.clone();
302
303 if !Self::unify_terms(pattern.0, fact.0, &mut new_substitution) {
304 return None;
305 }
306 if !Self::unify_terms(pattern.1, fact.1, &mut new_substitution) {
307 return None;
308 }
309 if !Self::unify_terms(pattern.2, fact.2, &mut new_substitution) {
310 return None;
311 }
312
313 PARALLEL_SUBSTITUTION_CLONES.inc();
315 Some(new_substitution)
316 }
317
318 fn unify_terms(pattern: &Term, fact: &Term, substitution: &mut HashMap<String, Term>) -> bool {
320 match (pattern, fact) {
321 (Term::Variable(var), fact_term) => {
322 if let Some(existing) = substitution.get(var) {
323 existing == fact_term
324 } else {
325 substitution.insert(var.clone(), fact_term.clone());
326 true
327 }
328 }
329 (Term::Constant(c1), Term::Constant(c2)) => c1 == c2,
330 (Term::Literal(l1), Term::Literal(l2)) => l1 == l2,
331 _ => false,
332 }
333 }
334
335 fn apply_substitution(atom: &RuleAtom, substitution: &HashMap<String, Term>) -> RuleAtom {
337 match atom {
338 RuleAtom::Triple {
339 subject,
340 predicate,
341 object,
342 } => RuleAtom::Triple {
343 subject: Self::substitute_term(subject, substitution),
344 predicate: Self::substitute_term(predicate, substitution),
345 object: Self::substitute_term(object, substitution),
346 },
347 _ => atom.clone(),
348 }
349 }
350
351 fn substitute_term(term: &Term, substitution: &HashMap<String, Term>) -> Term {
353 match term {
354 Term::Variable(var) => substitution
355 .get(var)
356 .cloned()
357 .unwrap_or_else(|| term.clone()),
358 _ => term.clone(),
359 }
360 }
361
362 pub fn get_stats(&self) -> ParallelStats {
364 let fact_count = self
365 .facts
366 .lock()
367 .expect("lock should not be poisoned")
368 .len();
369 ParallelStats {
370 num_threads: self.num_threads,
371 batch_size: self.batch_size,
372 total_facts: fact_count,
373 total_rules: self.rules.len(),
374 simd_enabled: self.simd_enabled,
375 }
376 }
377}
378
379#[derive(Debug, Clone)]
381pub struct ParallelStats {
382 pub num_threads: usize,
383 pub batch_size: usize,
384 pub total_facts: usize,
385 pub total_rules: usize,
386 pub simd_enabled: bool,
387}
388
389impl std::fmt::Display for ParallelStats {
390 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
391 write!(
392 f,
393 "Threads: {}, Batch: {}, Facts: {}, Rules: {}, SIMD: {}",
394 self.num_threads,
395 self.batch_size,
396 self.total_facts,
397 self.total_rules,
398 self.simd_enabled
399 )
400 }
401}
402
403pub mod simd {
407 use super::*;
408
409 pub fn simd_match_triples(
413 _patterns: &[RuleAtom],
414 _facts: &[RuleAtom],
415 ) -> Vec<HashMap<String, Term>> {
416 Vec::new()
419 }
420
421 pub fn simd_compare_terms(_terms1: &[Term], _terms2: &[Term]) -> Vec<bool> {
425 Vec::new()
427 }
428}
429
430#[cfg(test)]
431mod tests {
432 use super::*;
433
434 #[test]
435 fn test_parallel_engine() -> Result<(), Box<dyn std::error::Error>> {
436 let mut engine = ParallelEngine::new();
437
438 engine.add_rule(Rule {
439 name: "test".to_string(),
440 body: vec![RuleAtom::Triple {
441 subject: Term::Variable("X".to_string()),
442 predicate: Term::Constant("p".to_string()),
443 object: Term::Variable("Y".to_string()),
444 }],
445 head: vec![RuleAtom::Triple {
446 subject: Term::Variable("X".to_string()),
447 predicate: Term::Constant("q".to_string()),
448 object: Term::Variable("Y".to_string()),
449 }],
450 });
451
452 let facts = vec![RuleAtom::Triple {
453 subject: Term::Constant("a".to_string()),
454 predicate: Term::Constant("p".to_string()),
455 object: Term::Constant("b".to_string()),
456 }];
457
458 let result = engine.execute_parallel(&facts)?;
459 assert!(!result.is_empty());
460 Ok(())
461 }
462
463 #[test]
464 fn test_parallel_stats() {
465 let engine = ParallelEngine::new();
466 let stats = engine.get_stats();
467
468 assert!(stats.num_threads > 0);
469 assert!(stats.batch_size > 0);
470 }
471}