Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
Fix Reasoner.add_rule missing deduplication (#732)
KaifAhmad11d502d5e7425
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6941b54a..c158e27a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **`Reasoner.add_rule` had no deduplication, doubling rules and silently emptying `forward_chain()` on rerun** (#732) by @KaifAhmad1+ - `add_rule()` unconditionally appended to `self.rules`, so re-running the same setup code on an existing `Reasoner` instance (e.g. re-executing a Jupyter cell) duplicated every rule; since `forward_chain()` only records a conclusion if it isn't already in `self.facts`, the second run's duplicated rules matched but produced no new results, with no error or warning+ - `add_rule()` now compares an incoming rule's `rule_type`, `conditions`, and `conclusion` against existing rules and returns the existing `Rule` instead of appending a duplicate, keeping repeated `add_rule()` calls with the same definition idempotent+ - Added `test_add_rule_deduplicates_identical_rule`, `test_add_rule_deduplication_is_idempotent_across_forward_chain`, and `test_add_rule_does_not_dedupe_distinct_rules` regression tests+- **`InferenceResult.premises` always empty from `forward_chain`/`backward_chain`** (#739) by @Sameer6305- `_match_rule()` discarded matched facts and returned only instantiated conclusions, so `ExplanationGenerator` always produced empty premises lists regardless of which facts actually satisfied a rule, closing #733- `_match_rule()` now returns `(conclusion, matched_facts)` tuples; `forward_chain()` threads those facts into `InferenceResult(premises=...)`, merging premises when the same conclusion is derived more than once within a passdiff --git a/semantica/reasoning/reasoner.py b/semantica/reasoning/reasoner.pyindex 15aa781e..cfe2320b 100644--- a/semantica/reasoning/reasoner.py+++ b/semantica/reasoning/reasoner.py@@ -81,12 +81,31 @@ class Reasoner:self.rule_counter = 0def add_rule(self, rule_def: Union[str, Rule]) -> Rule:- """Add a rule to the reasoner."""+ """Add a rule to the reasoner.++ Rules with the same conditions and conclusion as an already-added+ rule are not re-appended -- this keeps re-running the same setup+ code (e.g. a Jupyter cell that calls add_rule() + add_fact() on an+ existing Reasoner) idempotent instead of silently duplicating rules+ on every rerun (#732).+ """if isinstance(rule_def, Rule):rule = rule_defelse:rule = self._parse_rule_definition(rule_def)-++ for existing in self.rules:+ if (+ existing.rule_type == rule.rule_type+ and existing.conditions == rule.conditions+ and existing.conclusion == rule.conclusion+ ):+ self.logger.debug(+ f"Skipping duplicate rule (same conditions/conclusion as '{existing.rule_id}'): "+ f"IF {' AND '.join(rule.conditions)} THEN {rule.conclusion}"+ )+ return existing+self.rules.append(rule)# Sort rules by priorityself.rules.sort(key=lambda r: r.priority, reverse=True)diff --git a/tests/reasoning/test_reasoner.py b/tests/reasoning/test_reasoner.pyindex cfd00feb..9552e5a2 100644--- a/tests/reasoning/test_reasoner.py+++ b/tests/reasoning/test_reasoner.py@@ -80,6 +80,42 @@ class TestReasoner(unittest.TestCase):self.assertIn("Person(John)", result.premises)self.assertIn("Parent(John, Jane)", result.premises)+ def test_add_rule_deduplicates_identical_rule(self):+ """Bug #732 — re-adding an identical rule string must not duplicate it,+ so re-running the same setup code (e.g. a Jupyter cell) is idempotent."""+ rule_str = "IF Person(?x) AND Parent(?x, ?y) THEN Child(?y, ?x)"+ first = self.reasoner.add_rule(rule_str)+ second = self.reasoner.add_rule(rule_str)++ self.assertEqual(len(self.reasoner.rules), 1)+ self.assertIs(first, second)++ def test_add_rule_deduplication_is_idempotent_across_forward_chain(self):+ """Bug #732 — rerunning add_rule()+add_fact()+forward_chain() on the same+ Reasoner instance must not grow the rule count on each call."""+ def run_cell():+ self.reasoner.add_rule("IF Person(?x) AND Parent(?x, ?y) THEN Child(?y, ?x)")+ self.reasoner.add_fact("Person(John)")+ self.reasoner.add_fact("Parent(John, Jane)")+ return self.reasoner.forward_chain()++ result1 = run_cell()+ self.assertEqual(len(self.reasoner.rules), 1)+ self.assertEqual([r.conclusion for r in result1], ["Child(Jane, John)"])++ result2 = run_cell()+ self.assertEqual(len(self.reasoner.rules), 1)+ # Nothing new to derive since the fact was already known -- this is+ # now a consistent, expected empty result rather than a symptom of+ # unbounded rule duplication.+ self.assertEqual(result2, [])++ def test_add_rule_does_not_dedupe_distinct_rules(self):+ """Rules with different conditions/conclusions must still both be added."""+ self.reasoner.add_rule("IF A(?x) THEN B(?x)")+ self.reasoner.add_rule("IF A(?x) THEN C(?x)")+ self.assertEqual(len(self.reasoner.rules), 2)+def test_infer_facts(self):facts = ["Person(John)", "Parent(John, Jane)"]rules = ["IF Person(?x) AND Parent(?x, ?y) THEN Child(?y, ?x)"]