Skip to main content

oxirs_rule/
rule_executor.rs

1//! Rule forward-chaining execution engine.
2//!
3//! This module provides a simple but correct forward-chaining rule execution
4//! engine that derives new facts from a dataset until a fixpoint is reached.
5//!
6//! # Architecture
7//!
8//! ```text
9//! Facts ──┐
10//!          ├──► RuleExecutor ──► ExecutionResult
11//! Rules ──┘
12//! ```
13//!
14//! Rules are represented as condition/head pairs where variable references
15//! `?var` are substituted during execution.
16
17use std::collections::{HashMap, HashSet};
18
19// ─── Data Types ───────────────────────────────────────────────────────────────
20
21/// An RDF-like fact (subject, predicate, object triple).
22#[derive(Debug, Clone, PartialEq, Eq, Hash)]
23pub struct Fact {
24    pub subject: String,
25    pub predicate: String,
26    pub object: String,
27}
28
29impl Fact {
30    pub fn new(
31        subject: impl Into<String>,
32        predicate: impl Into<String>,
33        object: impl Into<String>,
34    ) -> Self {
35        Self {
36            subject: subject.into(),
37            predicate: predicate.into(),
38            object: object.into(),
39        }
40    }
41}
42
43/// The head (consequent) of a rule — describes the fact to derive.
44///
45/// Fields may contain variable references such as `?x` that will be resolved
46/// using the binding produced by matching the rule conditions.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct RuleHead {
49    pub subject: String,
50    pub predicate: String,
51    pub object: String,
52}
53
54impl RuleHead {
55    pub fn new(
56        subject: impl Into<String>,
57        predicate: impl Into<String>,
58        object: impl Into<String>,
59    ) -> Self {
60        Self {
61            subject: subject.into(),
62            predicate: predicate.into(),
63            object: object.into(),
64        }
65    }
66}
67
68/// A single condition (antecedent) of a rule.
69///
70/// Each field is either a constant or a variable (`?var`).
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct RuleCondition {
73    pub subject: String,
74    pub predicate: String,
75    pub object: String,
76}
77
78impl RuleCondition {
79    pub fn new(
80        subject: impl Into<String>,
81        predicate: impl Into<String>,
82        object: impl Into<String>,
83    ) -> Self {
84        Self {
85            subject: subject.into(),
86            predicate: predicate.into(),
87            object: object.into(),
88        }
89    }
90}
91
92/// A production rule with a unique identifier, list of conditions, and a head.
93#[derive(Debug, Clone)]
94pub struct SimpleRule {
95    pub id: String,
96    pub conditions: Vec<RuleCondition>,
97    pub head: RuleHead,
98}
99
100impl SimpleRule {
101    pub fn new(id: impl Into<String>, conditions: Vec<RuleCondition>, head: RuleHead) -> Self {
102        Self {
103            id: id.into(),
104            conditions,
105            head,
106        }
107    }
108}
109
110/// Summary of a completed forward-chaining execution run.
111#[derive(Debug, Clone, Default)]
112pub struct ExecutionResult {
113    /// All newly derived facts (not present in the original input).
114    pub new_facts: Vec<Fact>,
115    /// Number of fixpoint iterations performed.
116    pub iterations: usize,
117    /// Total number of times a rule produced a new fact.
118    pub rules_fired: usize,
119}
120
121// ─── Rule Executor ───────────────────────────────────────────────────────────
122
123/// Forward-chaining rule execution engine.
124///
125/// Rules are applied iteratively until no new facts are produced (fixpoint).
126#[derive(Debug, Default)]
127pub struct RuleExecutor {
128    rules: Vec<SimpleRule>,
129}
130
131impl RuleExecutor {
132    /// Create a new `RuleExecutor` with no rules.
133    pub fn new() -> Self {
134        Self { rules: Vec::new() }
135    }
136
137    /// Add a rule to the executor.
138    pub fn add_rule(&mut self, rule: SimpleRule) {
139        self.rules.push(rule);
140    }
141
142    /// Return the number of registered rules.
143    pub fn rule_count(&self) -> usize {
144        self.rules.len()
145    }
146
147    /// Execute forward chaining until fixpoint.
148    ///
149    /// Returns an `ExecutionResult` containing all newly derived facts and
150    /// execution statistics.
151    pub fn execute(&self, facts: &[Fact]) -> ExecutionResult {
152        let mut all_facts: HashSet<Fact> = facts.iter().cloned().collect();
153        let original_facts: HashSet<Fact> = all_facts.clone();
154        let mut iterations = 0_usize;
155        let mut rules_fired = 0_usize;
156
157        loop {
158            let current_facts: Vec<Fact> = all_facts.iter().cloned().collect();
159            let new_in_step = self.execute_one_step_on(&current_facts);
160
161            let mut added_any = false;
162            for fact in new_in_step {
163                if all_facts.insert(fact) {
164                    added_any = true;
165                    rules_fired += 1;
166                }
167            }
168
169            iterations += 1;
170
171            if !added_any {
172                break;
173            }
174        }
175
176        let new_facts: Vec<Fact> = all_facts
177            .into_iter()
178            .filter(|f| !original_facts.contains(f))
179            .collect();
180
181        ExecutionResult {
182            new_facts,
183            iterations,
184            rules_fired,
185        }
186    }
187
188    /// Perform one forward-chaining iteration.
189    ///
190    /// Returns a list of candidate new facts (may include already-known ones).
191    pub fn execute_one_step(&self, facts: &[Fact]) -> Vec<Fact> {
192        self.execute_one_step_on(facts)
193    }
194
195    fn execute_one_step_on(&self, facts: &[Fact]) -> Vec<Fact> {
196        let mut derived = Vec::new();
197        for rule in &self.rules {
198            let bindings_list = self.match_conditions(facts, &rule.conditions);
199            for bindings in bindings_list {
200                let new_fact = self.apply_head(&rule.head, &bindings);
201                derived.push(new_fact);
202            }
203        }
204        derived
205    }
206
207    /// Find all variable assignments satisfying all rule conditions.
208    ///
209    /// Performs a nested-loop join across the conditions, accumulating
210    /// compatible bindings.
211    pub fn match_conditions(
212        &self,
213        facts: &[Fact],
214        conditions: &[RuleCondition],
215    ) -> Vec<HashMap<String, String>> {
216        if conditions.is_empty() {
217            // No conditions → one empty binding (rule always fires)
218            return vec![HashMap::new()];
219        }
220
221        let mut current: Vec<HashMap<String, String>> = vec![HashMap::new()];
222
223        for condition in conditions {
224            let mut next: Vec<HashMap<String, String>> = Vec::new();
225            for bindings in &current {
226                let matches = self.match_single_condition(facts, condition, bindings);
227                next.extend(matches);
228            }
229            current = next;
230        }
231
232        current
233    }
234
235    /// Match a single condition against all facts given existing bindings.
236    fn match_single_condition(
237        &self,
238        facts: &[Fact],
239        condition: &RuleCondition,
240        bindings: &HashMap<String, String>,
241    ) -> Vec<HashMap<String, String>> {
242        let mut results = Vec::new();
243        for fact in facts {
244            if let Some(new_bindings) = self.try_bind_condition(condition, fact, bindings) {
245                results.push(new_bindings);
246            }
247        }
248        results
249    }
250
251    /// Try to unify a condition with a fact given existing bindings.
252    fn try_bind_condition(
253        &self,
254        condition: &RuleCondition,
255        fact: &Fact,
256        bindings: &HashMap<String, String>,
257    ) -> Option<HashMap<String, String>> {
258        let mut new_bindings = bindings.clone();
259        new_bindings = Self::try_bind_term(&condition.subject, &fact.subject, new_bindings)?;
260        new_bindings = Self::try_bind_term(&condition.predicate, &fact.predicate, new_bindings)?;
261        new_bindings = Self::try_bind_term(&condition.object, &fact.object, new_bindings)?;
262        Some(new_bindings)
263    }
264
265    /// Try to bind a pattern term to a concrete value.
266    fn try_bind_term(
267        term: &str,
268        value: &str,
269        mut bindings: HashMap<String, String>,
270    ) -> Option<HashMap<String, String>> {
271        if Self::is_variable(term) {
272            let var_name = term.trim_start_matches('?').to_string();
273            if let Some(existing) = bindings.get(&var_name) {
274                if existing != value {
275                    return None;
276                }
277            } else {
278                bindings.insert(var_name, value.to_string());
279            }
280            Some(bindings)
281        } else if term == value {
282            Some(bindings)
283        } else {
284            None
285        }
286    }
287
288    /// Instantiate a rule head by substituting variables with bound values.
289    ///
290    /// Returns a concrete `Fact`.
291    pub fn apply_head(&self, head: &RuleHead, bindings: &HashMap<String, String>) -> Fact {
292        Fact {
293            subject: Self::resolve_term(&head.subject, bindings),
294            predicate: Self::resolve_term(&head.predicate, bindings),
295            object: Self::resolve_term(&head.object, bindings),
296        }
297    }
298
299    /// Resolve a term using bindings (substitute variable, or return constant).
300    fn resolve_term(term: &str, bindings: &HashMap<String, String>) -> String {
301        if Self::is_variable(term) {
302            let var_name = term.trim_start_matches('?');
303            bindings
304                .get(var_name)
305                .cloned()
306                .unwrap_or_else(|| term.to_string())
307        } else {
308            term.to_string()
309        }
310    }
311
312    /// Returns `true` if the term is a variable (starts with `?`).
313    fn is_variable(term: &str) -> bool {
314        term.starts_with('?')
315    }
316}
317
318// ─── Tests ───────────────────────────────────────────────────────────────────
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323
324    fn make_executor() -> RuleExecutor {
325        RuleExecutor::new()
326    }
327
328    // Helper to build a simple transitive-like rule:
329    // CONDITION: (?x type ?t), (?t subClassOf ?u)  =>  HEAD: (?x type ?u)
330    fn type_hierarchy_rule() -> SimpleRule {
331        SimpleRule::new(
332            "type-hierarchy",
333            vec![
334                RuleCondition::new("?x", "type", "?t"),
335                RuleCondition::new("?t", "subClassOf", "?u"),
336            ],
337            RuleHead::new("?x", "type", "?u"),
338        )
339    }
340
341    // ── rule_count ────────────────────────────────────────────────────────────
342
343    #[test]
344    fn test_rule_count_empty() {
345        let e = make_executor();
346        assert_eq!(e.rule_count(), 0);
347    }
348
349    #[test]
350    fn test_rule_count_after_add() {
351        let mut e = make_executor();
352        e.add_rule(type_hierarchy_rule());
353        assert_eq!(e.rule_count(), 1);
354    }
355
356    #[test]
357    fn test_rule_count_multiple() {
358        let mut e = make_executor();
359        for i in 0..5 {
360            e.add_rule(SimpleRule::new(
361                format!("r{i}"),
362                vec![],
363                RuleHead::new("a", "b", "c"),
364            ));
365        }
366        assert_eq!(e.rule_count(), 5);
367    }
368
369    // ── match_conditions ──────────────────────────────────────────────────────
370
371    #[test]
372    fn test_match_single_condition_one_fact() -> anyhow::Result<()> {
373        let e = make_executor();
374        let facts = vec![Fact::new(":Alice", "knows", ":Bob")];
375        let conditions = vec![RuleCondition::new("?x", "knows", ":Bob")];
376        let results = e.match_conditions(&facts, &conditions);
377        assert_eq!(results.len(), 1);
378        assert_eq!(results[0].get("x").map(|s| s.as_str()), Some(":Alice"));
379        Ok(())
380    }
381
382    #[test]
383    fn test_match_conditions_no_facts() -> anyhow::Result<()> {
384        let e = make_executor();
385        let facts: Vec<Fact> = vec![];
386        let conditions = vec![RuleCondition::new("?x", "knows", "?y")];
387        let results = e.match_conditions(&facts, &conditions);
388        assert!(results.is_empty());
389        Ok(())
390    }
391
392    #[test]
393    fn test_match_conditions_empty_conditions() {
394        let e = make_executor();
395        let facts = vec![Fact::new(":Alice", "knows", ":Bob")];
396        let results = e.match_conditions(&facts, &[]);
397        // No conditions → one empty binding
398        assert_eq!(results.len(), 1);
399        assert!(results[0].is_empty());
400    }
401
402    #[test]
403    fn test_match_conditions_multiple_facts() -> anyhow::Result<()> {
404        let e = make_executor();
405        let facts = vec![
406            Fact::new(":Alice", "knows", ":Bob"),
407            Fact::new(":Carol", "knows", ":Dave"),
408        ];
409        let conditions = vec![RuleCondition::new("?x", "knows", "?y")];
410        let results = e.match_conditions(&facts, &conditions);
411        assert_eq!(results.len(), 2);
412        Ok(())
413    }
414
415    #[test]
416    fn test_match_conditions_join_filters() -> anyhow::Result<()> {
417        let e = make_executor();
418        let facts = vec![
419            Fact::new(":Alice", "knows", ":Bob"),
420            Fact::new(":Bob", "knows", ":Carol"),
421            Fact::new(":Carol", "knows", ":Dave"),
422        ];
423        // (?x knows ?y) AND (?y knows ?z)
424        let conditions = vec![
425            RuleCondition::new("?x", "knows", "?y"),
426            RuleCondition::new("?y", "knows", "?z"),
427        ];
428        let results = e.match_conditions(&facts, &conditions);
429        assert_eq!(results.len(), 2); // Alice→Bob→Carol and Bob→Carol→Dave
430        Ok(())
431    }
432
433    // ── apply_head ────────────────────────────────────────────────────────────
434
435    #[test]
436    fn test_apply_head_all_constants() {
437        let e = make_executor();
438        let head = RuleHead::new(":Alice", "type", ":Person");
439        let bindings = HashMap::new();
440        let fact = e.apply_head(&head, &bindings);
441        assert_eq!(fact.subject, ":Alice");
442        assert_eq!(fact.predicate, "type");
443        assert_eq!(fact.object, ":Person");
444    }
445
446    #[test]
447    fn test_apply_head_variable_substitution() -> anyhow::Result<()> {
448        let e = make_executor();
449        let head = RuleHead::new("?x", "type", "?u");
450        let bindings: HashMap<String, String> = [
451            ("x".into(), ":Alice".into()),
452            ("u".into(), ":Person".into()),
453        ]
454        .into();
455        let fact = e.apply_head(&head, &bindings);
456        assert_eq!(fact.subject, ":Alice");
457        assert_eq!(fact.object, ":Person");
458        Ok(())
459    }
460
461    #[test]
462    fn test_apply_head_unbound_variable_kept() -> anyhow::Result<()> {
463        let e = make_executor();
464        let head = RuleHead::new("?x", "type", "?unbound");
465        let bindings: HashMap<String, String> = [("x".into(), ":Alice".into())].into();
466        let fact = e.apply_head(&head, &bindings);
467        assert_eq!(fact.subject, ":Alice");
468        assert_eq!(fact.object, "?unbound"); // kept as-is
469        Ok(())
470    }
471
472    // ── execute (simple) ───────────────────────────────────────────────────────
473
474    #[test]
475    fn test_execute_no_rules_no_new_facts() {
476        let e = make_executor();
477        let facts = vec![Fact::new(":Alice", "knows", ":Bob")];
478        let result = e.execute(&facts);
479        assert!(result.new_facts.is_empty());
480        assert_eq!(result.iterations, 1);
481    }
482
483    #[test]
484    fn test_execute_simple_rule_fires() -> anyhow::Result<()> {
485        let mut e = make_executor();
486        // knows(?x, ?y) → knows_transitively(?x, ?y)
487        e.add_rule(SimpleRule::new(
488            "copy-knows",
489            vec![RuleCondition::new("?x", "knows", "?y")],
490            RuleHead::new("?x", "knows_transitively", "?y"),
491        ));
492        let facts = vec![Fact::new(":Alice", "knows", ":Bob")];
493        let result = e.execute(&facts);
494        assert_eq!(result.new_facts.len(), 1);
495        assert_eq!(result.new_facts[0].predicate, "knows_transitively");
496        Ok(())
497    }
498
499    #[test]
500    fn test_execute_fixpoint_one_iteration() {
501        let mut e = make_executor();
502        e.add_rule(SimpleRule::new(
503            "const-fact",
504            vec![],
505            RuleHead::new(":A", "prop", ":B"),
506        ));
507        let facts: Vec<Fact> = vec![];
508        let result = e.execute(&facts);
509        // Rule fires once; next iteration finds it already present
510        assert_eq!(result.new_facts.len(), 1);
511        assert!(result.iterations >= 1);
512    }
513
514    #[test]
515    fn test_execute_transitive_closure() -> anyhow::Result<()> {
516        let mut e = make_executor();
517        // knows(?x, ?y) ∧ knows(?y, ?z) → knows(?x, ?z)
518        e.add_rule(SimpleRule::new(
519            "transitivity",
520            vec![
521                RuleCondition::new("?x", "knows", "?y"),
522                RuleCondition::new("?y", "knows", "?z"),
523            ],
524            RuleHead::new("?x", "knows", "?z"),
525        ));
526        let facts = vec![
527            Fact::new(":A", "knows", ":B"),
528            Fact::new(":B", "knows", ":C"),
529        ];
530        let result = e.execute(&facts);
531        let derived = Fact::new(":A", "knows", ":C");
532        assert!(result.new_facts.contains(&derived));
533        Ok(())
534    }
535
536    #[test]
537    fn test_execute_chain_three_hops() -> anyhow::Result<()> {
538        let mut e = make_executor();
539        e.add_rule(SimpleRule::new(
540            "transitivity",
541            vec![
542                RuleCondition::new("?x", "link", "?y"),
543                RuleCondition::new("?y", "link", "?z"),
544            ],
545            RuleHead::new("?x", "link", "?z"),
546        ));
547        let facts = vec![
548            Fact::new(":A", "link", ":B"),
549            Fact::new(":B", "link", ":C"),
550            Fact::new(":C", "link", ":D"),
551        ];
552        let result = e.execute(&facts);
553        let fact_ac = Fact::new(":A", "link", ":C");
554        let fact_bd = Fact::new(":B", "link", ":D");
555        let fact_ad = Fact::new(":A", "link", ":D");
556        assert!(result.new_facts.contains(&fact_ac));
557        assert!(result.new_facts.contains(&fact_bd));
558        assert!(result.new_facts.contains(&fact_ad));
559        Ok(())
560    }
561
562    #[test]
563    fn test_execute_type_hierarchy_rule() {
564        let mut e = make_executor();
565        e.add_rule(type_hierarchy_rule());
566        let facts = vec![
567            Fact::new(":Alice", "type", ":Employee"),
568            Fact::new(":Employee", "subClassOf", ":Person"),
569        ];
570        let result = e.execute(&facts);
571        let expected = Fact::new(":Alice", "type", ":Person");
572        assert!(result.new_facts.contains(&expected));
573    }
574
575    #[test]
576    fn test_execute_empty_fact_set() -> anyhow::Result<()> {
577        let mut e = make_executor();
578        e.add_rule(SimpleRule::new(
579            "transitivity",
580            vec![
581                RuleCondition::new("?x", "knows", "?y"),
582                RuleCondition::new("?y", "knows", "?z"),
583            ],
584            RuleHead::new("?x", "knows", "?z"),
585        ));
586        let result = e.execute(&[]);
587        assert!(result.new_facts.is_empty());
588        Ok(())
589    }
590
591    #[test]
592    fn test_execute_no_new_facts_fixpoint_stats() -> anyhow::Result<()> {
593        let mut e = make_executor();
594        // Rule that could fire but won't produce anything new if base fact exists
595        e.add_rule(SimpleRule::new(
596            "reflexive",
597            vec![RuleCondition::new("?x", "knows", "?y")],
598            RuleHead::new("?x", "knows", "?y"), // same as condition
599        ));
600        let facts = vec![Fact::new(":Alice", "knows", ":Bob")];
601        let result = e.execute(&facts);
602        assert!(result.new_facts.is_empty());
603        // rules_fired should be 0 since no genuinely new facts were added
604        assert_eq!(result.rules_fired, 0);
605        Ok(())
606    }
607
608    #[test]
609    fn test_execute_multiple_rules_chain() -> anyhow::Result<()> {
610        let mut e = make_executor();
611        // Rule 1: knows(?x,?y) → acquaintance(?x,?y)
612        e.add_rule(SimpleRule::new(
613            "r1",
614            vec![RuleCondition::new("?x", "knows", "?y")],
615            RuleHead::new("?x", "acquaintance", "?y"),
616        ));
617        // Rule 2: acquaintance(?x,?y) → acquaintance(?y,?x)
618        e.add_rule(SimpleRule::new(
619            "r2",
620            vec![RuleCondition::new("?x", "acquaintance", "?y")],
621            RuleHead::new("?y", "acquaintance", "?x"),
622        ));
623        let facts = vec![Fact::new(":Alice", "knows", ":Bob")];
624        let result = e.execute(&facts);
625        let fwd = Fact::new(":Alice", "acquaintance", ":Bob");
626        let bwd = Fact::new(":Bob", "acquaintance", ":Alice");
627        assert!(result.new_facts.contains(&fwd));
628        assert!(result.new_facts.contains(&bwd));
629        Ok(())
630    }
631
632    #[test]
633    fn test_execute_multiple_bindings_produce_multiple_facts() -> anyhow::Result<()> {
634        let mut e = make_executor();
635        e.add_rule(SimpleRule::new(
636            "copy",
637            vec![RuleCondition::new("?x", "knows", "?y")],
638            RuleHead::new("?x", "met", "?y"),
639        ));
640        let facts = vec![
641            Fact::new(":Alice", "knows", ":Bob"),
642            Fact::new(":Alice", "knows", ":Carol"),
643            Fact::new(":Bob", "knows", ":Dave"),
644        ];
645        let result = e.execute(&facts);
646        assert_eq!(result.new_facts.len(), 3);
647        Ok(())
648    }
649
650    // ── execute_one_step ──────────────────────────────────────────────────────
651
652    #[test]
653    fn test_execute_one_step_basic() -> anyhow::Result<()> {
654        let mut e = make_executor();
655        e.add_rule(SimpleRule::new(
656            "copy",
657            vec![RuleCondition::new("?x", "knows", "?y")],
658            RuleHead::new("?x", "met", "?y"),
659        ));
660        let facts = vec![Fact::new(":Alice", "knows", ":Bob")];
661        let derived = e.execute_one_step(&facts);
662        assert!(derived.contains(&Fact::new(":Alice", "met", ":Bob")));
663        Ok(())
664    }
665
666    #[test]
667    fn test_execute_one_step_empty_facts() {
668        let mut e = make_executor();
669        e.add_rule(type_hierarchy_rule());
670        let derived = e.execute_one_step(&[]);
671        assert!(derived.is_empty());
672    }
673
674    #[test]
675    fn test_execute_rules_fired_counter() -> anyhow::Result<()> {
676        let mut e = make_executor();
677        e.add_rule(SimpleRule::new(
678            "copy",
679            vec![RuleCondition::new("?x", "knows", "?y")],
680            RuleHead::new("?x", "met", "?y"),
681        ));
682        let facts = vec![
683            Fact::new(":A", "knows", ":B"),
684            Fact::new(":A", "knows", ":C"),
685        ];
686        let result = e.execute(&facts);
687        assert_eq!(result.rules_fired, 2);
688        Ok(())
689    }
690
691    #[test]
692    fn test_execute_iterations_greater_than_one_for_chain() -> anyhow::Result<()> {
693        let mut e = make_executor();
694        e.add_rule(SimpleRule::new(
695            "transitivity",
696            vec![
697                RuleCondition::new("?x", "p", "?y"),
698                RuleCondition::new("?y", "p", "?z"),
699            ],
700            RuleHead::new("?x", "p", "?z"),
701        ));
702        let facts = vec![
703            Fact::new(":A", "p", ":B"),
704            Fact::new(":B", "p", ":C"),
705            Fact::new(":C", "p", ":D"),
706        ];
707        let result = e.execute(&facts);
708        assert!(
709            result.iterations >= 2,
710            "expected at least 2 iterations for 3-hop chain"
711        );
712        Ok(())
713    }
714
715    // ── additional edge cases and scenarios ────────────────────────────────────
716
717    #[test]
718    fn test_add_multiple_rules_independent() -> anyhow::Result<()> {
719        let mut e = make_executor();
720        e.add_rule(SimpleRule::new(
721            "r1",
722            vec![RuleCondition::new("?x", "a", "?y")],
723            RuleHead::new("?x", "b", "?y"),
724        ));
725        e.add_rule(SimpleRule::new(
726            "r2",
727            vec![RuleCondition::new("?x", "b", "?y")],
728            RuleHead::new("?x", "c", "?y"),
729        ));
730        assert_eq!(e.rule_count(), 2);
731        Ok(())
732    }
733
734    #[test]
735    fn test_execute_constant_head_rule() {
736        // A rule with no conditions and a constant head produces exactly one fact.
737        let mut e = make_executor();
738        e.add_rule(SimpleRule::new(
739            "const",
740            vec![],
741            RuleHead::new(":Universe", "exists", "true"),
742        ));
743        let result = e.execute(&[]);
744        assert_eq!(result.new_facts.len(), 1);
745        assert_eq!(result.new_facts[0].subject, ":Universe");
746    }
747
748    #[test]
749    fn test_execute_self_loop_no_infinite_loop() -> anyhow::Result<()> {
750        // Rule: (?x knows ?y) → (?x knows ?y) — should terminate because fixpoint is immediate.
751        let mut e = make_executor();
752        e.add_rule(SimpleRule::new(
753            "loop",
754            vec![RuleCondition::new("?x", "knows", "?y")],
755            RuleHead::new("?x", "knows", "?y"),
756        ));
757        let facts = vec![Fact::new(":A", "knows", ":B")];
758        let result = e.execute(&facts);
759        assert!(
760            result.new_facts.is_empty(),
761            "reflexive rule produces no new facts"
762        );
763        Ok(())
764    }
765
766    #[test]
767    fn test_match_conditions_constant_triple() {
768        let e = make_executor();
769        let facts = vec![
770            Fact::new(":X", "rdf:type", ":Class"),
771            Fact::new(":Y", "rdf:type", ":OtherClass"),
772        ];
773        let conditions = vec![RuleCondition::new(":X", "rdf:type", ":Class")];
774        let results = e.match_conditions(&facts, &conditions);
775        assert_eq!(results.len(), 1);
776        assert!(results[0].is_empty(), "no variables to bind");
777    }
778
779    #[test]
780    fn test_match_conditions_no_match_for_constant() {
781        let e = make_executor();
782        let facts = vec![Fact::new(":Alice", "knows", ":Bob")];
783        let conditions = vec![RuleCondition::new(":Carol", "knows", ":Bob")];
784        let results = e.match_conditions(&facts, &conditions);
785        assert!(results.is_empty());
786    }
787
788    #[test]
789    fn test_apply_head_mixed_const_and_var() -> anyhow::Result<()> {
790        let e = make_executor();
791        let head = RuleHead::new("?x", "rdf:type", ":Person");
792        let bindings: HashMap<String, String> = [("x".into(), ":Alice".into())].into();
793        let fact = e.apply_head(&head, &bindings);
794        assert_eq!(fact.subject, ":Alice");
795        assert_eq!(fact.predicate, "rdf:type");
796        assert_eq!(fact.object, ":Person");
797        Ok(())
798    }
799
800    #[test]
801    fn test_execute_symmetric_rule() -> anyhow::Result<()> {
802        let mut e = make_executor();
803        // knows(?x, ?y) → knows(?y, ?x)
804        e.add_rule(SimpleRule::new(
805            "symmetric",
806            vec![RuleCondition::new("?x", "knows", "?y")],
807            RuleHead::new("?y", "knows", "?x"),
808        ));
809        let facts = vec![Fact::new(":Alice", "knows", ":Bob")];
810        let result = e.execute(&facts);
811        assert!(result
812            .new_facts
813            .contains(&Fact::new(":Bob", "knows", ":Alice")));
814        Ok(())
815    }
816
817    #[test]
818    fn test_execute_multi_hop_class_hierarchy() -> anyhow::Result<()> {
819        let mut e = make_executor();
820        // subClassOf(?a, ?b) ∧ subClassOf(?b, ?c) → subClassOf(?a, ?c)
821        e.add_rule(SimpleRule::new(
822            "transitive-subclass",
823            vec![
824                RuleCondition::new("?a", "subClassOf", "?b"),
825                RuleCondition::new("?b", "subClassOf", "?c"),
826            ],
827            RuleHead::new("?a", "subClassOf", "?c"),
828        ));
829        let facts = vec![
830            Fact::new(":Manager", "subClassOf", ":Employee"),
831            Fact::new(":Employee", "subClassOf", ":Person"),
832            Fact::new(":Person", "subClassOf", ":Agent"),
833        ];
834        let result = e.execute(&facts);
835        assert!(result
836            .new_facts
837            .contains(&Fact::new(":Manager", "subClassOf", ":Person")));
838        assert!(result
839            .new_facts
840            .contains(&Fact::new(":Employee", "subClassOf", ":Agent")));
841        assert!(result
842            .new_facts
843            .contains(&Fact::new(":Manager", "subClassOf", ":Agent")));
844        Ok(())
845    }
846
847    #[test]
848    fn test_execute_new_facts_excludes_input() -> anyhow::Result<()> {
849        let mut e = make_executor();
850        e.add_rule(SimpleRule::new(
851            "copy",
852            vec![RuleCondition::new("?x", "knows", "?y")],
853            RuleHead::new("?x", "met", "?y"),
854        ));
855        let input_fact = Fact::new(":Alice", "knows", ":Bob");
856        let result = e.execute(std::slice::from_ref(&input_fact));
857        // Original fact must NOT appear in new_facts
858        assert!(!result.new_facts.contains(&input_fact));
859        Ok(())
860    }
861
862    #[test]
863    fn test_execute_no_rules_preserves_input() {
864        let e = make_executor();
865        let facts = vec![Fact::new(":A", "b", ":C"), Fact::new(":D", "e", ":F")];
866        let result = e.execute(&facts);
867        assert!(result.new_facts.is_empty());
868        assert_eq!(result.iterations, 1);
869    }
870
871    #[test]
872    fn test_execute_one_step_returns_duplicates_ok() -> anyhow::Result<()> {
873        // execute_one_step may return duplicate facts (deduplication is done in execute).
874        let mut e = make_executor();
875        e.add_rule(SimpleRule::new(
876            "copy1",
877            vec![RuleCondition::new("?x", "p", "?y")],
878            RuleHead::new("?x", "q", "?y"),
879        ));
880        e.add_rule(SimpleRule::new(
881            "copy2",
882            vec![RuleCondition::new("?x", "p", "?y")],
883            RuleHead::new("?x", "q", "?y"),
884        ));
885        let facts = vec![Fact::new(":A", "p", ":B")];
886        let derived = e.execute_one_step(&facts);
887        // Both rules produce the same fact → 2 entries (duplicates allowed in one-step output)
888        assert_eq!(derived.len(), 2);
889        Ok(())
890    }
891
892    #[test]
893    fn test_execute_deduplicates_across_rules() -> anyhow::Result<()> {
894        // execute() deduplicates: two rules producing the same fact count as rules_fired=1.
895        let mut e = make_executor();
896        e.add_rule(SimpleRule::new(
897            "copy1",
898            vec![RuleCondition::new("?x", "p", "?y")],
899            RuleHead::new("?x", "q", "?y"),
900        ));
901        e.add_rule(SimpleRule::new(
902            "copy2",
903            vec![RuleCondition::new("?x", "p", "?y")],
904            RuleHead::new("?x", "q", "?y"),
905        ));
906        let facts = vec![Fact::new(":A", "p", ":B")];
907        let result = e.execute(&facts);
908        // Deduplicated: only 1 genuinely new fact
909        assert_eq!(result.new_facts.len(), 1);
910        Ok(())
911    }
912
913    #[test]
914    fn test_fact_equality() {
915        let f1 = Fact::new(":A", "p", ":B");
916        let f2 = Fact::new(":A", "p", ":B");
917        let f3 = Fact::new(":A", "p", ":C");
918        assert_eq!(f1, f2);
919        assert_ne!(f1, f3);
920    }
921
922    #[test]
923    fn test_rule_with_three_conditions() -> anyhow::Result<()> {
924        let mut e = make_executor();
925        // (?x p ?y) ∧ (?y p ?z) ∧ (?z p ?w) → (?x skip3 ?w)
926        e.add_rule(SimpleRule::new(
927            "skip3",
928            vec![
929                RuleCondition::new("?x", "p", "?y"),
930                RuleCondition::new("?y", "p", "?z"),
931                RuleCondition::new("?z", "p", "?w"),
932            ],
933            RuleHead::new("?x", "skip3", "?w"),
934        ));
935        let facts = vec![
936            Fact::new(":A", "p", ":B"),
937            Fact::new(":B", "p", ":C"),
938            Fact::new(":C", "p", ":D"),
939        ];
940        let result = e.execute(&facts);
941        assert!(result.new_facts.contains(&Fact::new(":A", "skip3", ":D")));
942        Ok(())
943    }
944
945    #[test]
946    fn test_match_conditions_variable_reuse_across_conditions() -> anyhow::Result<()> {
947        // Ensure that a variable bound in condition 1 constrains condition 2.
948        let e = make_executor();
949        let facts = vec![
950            Fact::new(":X", "type", ":A"),
951            Fact::new(":X", "type", ":B"),
952            Fact::new(":Y", "type", ":A"),
953        ];
954        // Condition: (?s type ?t) ∧ (?s type :A) — second condition uses constant :A
955        let conditions = vec![
956            RuleCondition::new("?s", "type", "?t"),
957            RuleCondition::new("?s", "type", ":A"),
958        ];
959        let results = e.match_conditions(&facts, &conditions);
960        // :X has type :A and :B; :Y has type :A.
961        // Solutions where s=:X and t in {:A,:B}, plus s=:Y and t=:A.
962        assert_eq!(results.len(), 3);
963        Ok(())
964    }
965
966    #[test]
967    fn test_simple_rule_new_constructor() -> anyhow::Result<()> {
968        let rule = SimpleRule::new(
969            "test-rule",
970            vec![RuleCondition::new("?x", "p", "?y")],
971            RuleHead::new("?x", "q", "?y"),
972        );
973        assert_eq!(rule.id, "test-rule");
974        assert_eq!(rule.conditions.len(), 1);
975        Ok(())
976    }
977
978    #[test]
979    fn test_rule_condition_new_constructor() -> anyhow::Result<()> {
980        let cond = RuleCondition::new("?subject", "predicate", "object");
981        assert_eq!(cond.subject, "?subject");
982        assert_eq!(cond.predicate, "predicate");
983        assert_eq!(cond.object, "object");
984        Ok(())
985    }
986
987    #[test]
988    fn test_rule_head_new_constructor() -> anyhow::Result<()> {
989        let head = RuleHead::new("subject", "predicate", "?object");
990        assert_eq!(head.subject, "subject");
991        assert_eq!(head.predicate, "predicate");
992        assert_eq!(head.object, "?object");
993        Ok(())
994    }
995
996    #[test]
997    fn test_execution_result_default() {
998        let result = ExecutionResult::default();
999        assert!(result.new_facts.is_empty());
1000        assert_eq!(result.iterations, 0);
1001        assert_eq!(result.rules_fired, 0);
1002    }
1003
1004    #[test]
1005    fn test_execute_two_independent_rules_same_input() -> anyhow::Result<()> {
1006        let mut e = make_executor();
1007        e.add_rule(SimpleRule::new(
1008            "rule-a",
1009            vec![RuleCondition::new("?x", "knows", "?y")],
1010            RuleHead::new("?x", "met", "?y"),
1011        ));
1012        e.add_rule(SimpleRule::new(
1013            "rule-b",
1014            vec![RuleCondition::new("?x", "knows", "?y")],
1015            RuleHead::new("?y", "known_by", "?x"),
1016        ));
1017        let facts = vec![Fact::new(":Alice", "knows", ":Bob")];
1018        let result = e.execute(&facts);
1019        assert!(result
1020            .new_facts
1021            .contains(&Fact::new(":Alice", "met", ":Bob")));
1022        assert!(result
1023            .new_facts
1024            .contains(&Fact::new(":Bob", "known_by", ":Alice")));
1025        assert_eq!(result.new_facts.len(), 2);
1026        Ok(())
1027    }
1028}