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(reasoning): reject arity-mismatched facts (#1720)
hiro-nikaitoue217811d1ef7
diff --git a/semantica/reasoning/rete_engine.py b/semantica/reasoning/rete_engine.pyindex 68551de1..547425a8 100644--- a/semantica/reasoning/rete_engine.py+++ b/semantica/reasoning/rete_engine.py@@ -85,6 +85,41 @@ def _build_condition_regex(return f"^{p_regex}$"+def _count_pattern_arity(pattern: str) -> int:+ """Return the number of top-level arguments in a condition pattern.++ Walks the argument section of ``pattern`` while tracking parenthesis+ depth so that commas inside nested calls (e.g. ``f(?x, g(?y, ?z))``)+ are not counted as top-level argument separators.++ Args:+ pattern: A condition pattern string such as ``"knows(?x, ?y)"`` or+ ``"pred(a, f(?z), ?w)"``.++ Returns:+ The number of top-level arguments (0 for patterns with no opening+ parenthesis or for the empty-args form ``"pred()"``).+ """+ paren_pos = pattern.find("(")+ if paren_pos == -1:+ return 0 # No argument list at all.+ args_section = pattern[paren_pos + 1 :]+ if args_section.startswith(")"):+ return 0 # Empty argument list: pred().+ depth = 0+ top_level_commas = 0+ for ch in args_section:+ if ch == "(":+ depth += 1+ elif ch == ")":+ if depth == 0:+ break # Reached the closing paren of the top-level call.+ depth -= 1+ elif ch == "," and depth == 0:+ top_level_commas += 1+ return top_level_commas + 1++def unify_condition(condition: Any,fact: Fact,@@ -115,6 +150,13 @@ def unify_condition(pattern = condition if isinstance(condition, str) else str(condition)fact_str = str(fact)+ # Structural arity check: compare the parsed argument count from the+ # condition pattern against the actual Fact.arguments list. This uses+ # only structured data (Fact.arguments) and a one-time pattern walk, so+ # it is immune to commas inside argument values or nested calls.+ if _count_pattern_arity(pattern) != len(fact.arguments):+ return None+# Build the anchored regex once (variables already bound are inlined as# literals). See ``_build_condition_regex`` for the segment handling.p_regex = _build_condition_regex(pattern, bindings)@@ -201,6 +243,12 @@ class AlphaNode(ReteNode):# and every incoming fact reuses this compiled matcher instead of# rebuilding it (avoids repeated regex construction overhead).pattern = condition if isinstance(condition, str) else str(condition)+ # Parse the expected argument count once from the pattern so that+ # _matches() can reject arity-mismatched facts before running the+ # compiled regex. This uses structural pattern information (a+ # paren-depth walk), not fact string rendering, so it is immune to+ # commas inside argument values.+ self._condition_arity: int = _count_pattern_arity(pattern)self._compiled: Optional[re.Pattern] = Nonetry:self._compiled = re.compile(_build_condition_regex(pattern))@@ -236,6 +284,12 @@ class AlphaNode(ReteNode):matches, otherwise ``None``. An empty dict signals a match with novariables (still distinct from ``None``)."""+ # Fast structural arity gate: reject before running the regex.+ # Uses Fact.arguments (structured) vs self._condition_arity (parsed+ # once at init time from the pattern). Immune to commas inside+ # argument values because it never touches the rendered fact string.+ if len(fact.arguments) != self._condition_arity:+ return Noneif self._compiled is None:# Compilation failed at build time; treat as non-matching.return Nonediff --git a/tests/reasoning/test_rete_engine.py b/tests/reasoning/test_rete_engine.pyindex cc43e9c6..f2e25ffe 100644--- a/tests/reasoning/test_rete_engine.py+++ b/tests/reasoning/test_rete_engine.py@@ -1,8 +1,13 @@-"""Tests for the RETE engine pattern matching (issue #300).+"""Tests for the RETE engine pattern matching (issue #300, PR #1720).These tests verify that ``AlphaNode._matches`` and ``BetaNode._can_join`` nolonger behave like the old always-``True`` stubs, and that the network as awhole only fires rules whose conditions actually unify with the facts.++``TestArityMismatchRejection`` (PR #1720) specifically guards the fix for the+arity-mismatch bug where lazy ``.+?`` regex groups absorbed surplus arguments.+It exercises all three execution paths: ``unify_condition()``,+``AlphaNode._matches()``, and ``ReteEngine.add_fact()``."""import itertools@@ -49,11 +54,14 @@ class TestUnifyCondition(unittest.TestCase):def test_regex_error_logs_warning_and_returns_none(self):"""A regex compilation error is logged with context and yields None."""fact = Fact("f6", "Person", ["John"])- with mock.patch.object(- rete_engine.re,- "match",- side_effect=re.error("bad pattern"),- ), self.assertLogs("semantica.rete_engine", level="WARNING") as captured:+ with (+ mock.patch.object(+ rete_engine.re,+ "match",+ side_effect=re.error("bad pattern"),+ ),+ self.assertLogs("semantica.rete_engine", level="WARNING") as captured,+ ):result = unify_condition("Person(?x)", fact)self.assertIsNone(result)joined = "\n".join(captured.output)@@ -64,11 +72,14 @@ class TestUnifyCondition(unittest.TestCase):def test_unexpected_error_logs_warning_and_returns_none(self):"""An unexpected error is also logged and swallowed as None."""fact = Fact("f7", "Person", ["John"])- with mock.patch.object(- rete_engine.re,- "match",- side_effect=RuntimeError("boom"),- ), self.assertLogs("semantica.rete_engine", level="WARNING") as captured:+ with (+ mock.patch.object(+ rete_engine.re,+ "match",+ side_effect=RuntimeError("boom"),+ ),+ self.assertLogs("semantica.rete_engine", level="WARNING") as captured,+ ):result = unify_condition("Person(?x)", fact)self.assertIsNone(result)self.assertIn("boom", "\n".join(captured.output))@@ -106,11 +117,14 @@ class TestAlphaNode(unittest.TestCase):def test_bad_condition_never_matches_and_logs(self):"""A condition that fails to compile logs a warning and never fires."""- with mock.patch.object(- rete_engine,- "_build_condition_regex",- return_value="(unbalanced",- ), self.assertLogs("semantica.rete_engine", level="WARNING") as captured:+ with (+ mock.patch.object(+ rete_engine,+ "_build_condition_regex",+ return_value="(unbalanced",+ ),+ self.assertLogs("semantica.rete_engine", level="WARNING") as captured,+ ):node = AlphaNode("bad", "Person(?x)")self.assertIsNone(node._compiled)self.assertIn("failed to compile", "\n".join(captured.output))@@ -362,5 +376,290 @@ class TestThreeConditionChain(unittest.TestCase):self.assertEqual(engine.match_patterns(), [])+class TestCountPatternArity(unittest.TestCase):+ """Unit tests for the ``_count_pattern_arity`` helper (issue #1720).++ This function is the structural source-of-truth for how many arguments+ a condition pattern declares. It must handle nested calls, zero-arg+ forms, and patterns with no parentheses without touching the rendered+ fact string.+ """++ def setUp(self):+ from semantica.reasoning.rete_engine import _count_pattern_arity++ self._arity = _count_pattern_arity++ def test_one_variable(self):+ self.assertEqual(self._arity("Person(?x)"), 1)++ def test_two_variables(self):+ self.assertEqual(self._arity("Parent(?x, ?y)"), 2)++ def test_three_variables(self):+ self.assertEqual(self._arity("Located(?x, ?y, ?z)"), 3)++ def test_mixed_literal_and_variable(self):+ self.assertEqual(self._arity("knows(Doe, John, ?y)"), 3)++ def test_all_literals(self):+ self.assertEqual(self._arity("pred(a, b, c)"), 3)++ def test_zero_args(self):+ self.assertEqual(self._arity("axiom()"), 0)++ def test_no_parens(self):+ self.assertEqual(self._arity("no_parens"), 0)++ def test_nested_call_counts_as_one_arg(self):+ """A nested call ``f(?y, ?z)`` is a single top-level argument."""+ self.assertEqual(self._arity("pred(?x, f(?y, ?z), ?w)"), 3)++ def test_double_nested(self):+ self.assertEqual(self._arity("pred(f(a, g(b, c)), d)"), 2)++ def test_repeated_variable(self):+ self.assertEqual(self._arity("Loves(?x, ?x)"), 2)+++class TestArityMismatchRejection(unittest.TestCase):+ """Regression tests for the arity-mismatch bug (PR #1720 / issue #1720).++ The original bug: ``_build_condition_regex`` uses lazy ``.+?`` groups+ anchored with ``$``, so a fact with *more* arguments than the condition+ declares would still match — the last variable absorbed all surplus+ arguments as a single comma-separated string.++ These tests verify the fix at *every* layer of the Rete execution path:+ 1. ``unify_condition()`` — utility function+ 2. ``AlphaNode._matches()`` / ``AlphaNode.add_fact()`` — alpha filter+ 3. ``ReteEngine.add_fact()`` — full network propagation+ """++ # ------------------------------------------------------------------ #+ # Required mismatch cases (must all return None / produce no match) #+ # ------------------------------------------------------------------ #++ def test_extra_arg_via_unify_condition(self):+ """parent(?x, ?y) must not match a 3-argument fact."""+ self.assertIsNone(+ unify_condition("parent(?x, ?y)", Fact("f", "parent", ["a", "b", "c"]))+ )++ def test_extra_arg_via_alpha_node(self):+ """AlphaNode must reject the same 3-argument fact."""+ node = AlphaNode("a1", "parent(?x, ?y)")+ self.assertIsNone(node.add_fact(Fact("f", "parent", ["a", "b", "c"])))++ def test_extra_arg_via_rete_engine(self):+ """ReteEngine must not fire a rule for a fact with too many arguments."""+ engine = ReteEngine()+ engine.build_network(+ [+ Rule(+ rule_id="r",+ name="t",+ conditions=["parent(?x, ?y)"],+ conclusion="ok",+ )+ ]+ )+ engine.add_fact(Fact("f", "parent", ["a", "b", "c"]))+ self.assertEqual(engine.match_patterns(), [])++ def test_trusts_extra_arg_via_unify_condition(self):+ """trusts(?x) must not match a 2-argument fact."""+ self.assertIsNone(+ unify_condition("trusts(?x)", Fact("f", "trusts", ["a", "b"]))+ )++ def test_trusts_extra_arg_via_alpha_node(self):+ node = AlphaNode("a1", "trusts(?x)")+ self.assertIsNone(node.add_fact(Fact("f", "trusts", ["a", "b"])))++ def test_trusts_extra_arg_via_rete_engine(self):+ engine = ReteEngine()+ engine.build_network(+ [Rule(rule_id="r", name="t", conditions=["trusts(?x)"], conclusion="ok")]+ )+ engine.add_fact(Fact("f", "trusts", ["a", "b"]))+ self.assertEqual(engine.match_patterns(), [])++ def test_knows_extra_arg_via_unify_condition(self):+ """knows(?x) must not match a 2-argument fact."""+ self.assertIsNone(+ unify_condition("knows(?x)", Fact("f", "knows", ["Doe", "John"]))+ )++ def test_knows_extra_arg_via_alpha_node(self):+ node = AlphaNode("a1", "knows(?x)")+ self.assertIsNone(node.add_fact(Fact("f", "knows", ["Doe", "John"])))++ def test_knows_extra_arg_via_rete_engine(self):+ engine = ReteEngine()+ engine.build_network(+ [Rule(rule_id="r", name="t", conditions=["knows(?x)"], conclusion="ok")]+ )+ engine.add_fact(Fact("f", "knows", ["Doe", "John"]))+ self.assertEqual(engine.match_patterns(), [])++ # ------------------------------------------------------------------ #+ # Too-few-argument cases #+ # ------------------------------------------------------------------ #++ def test_too_few_args_via_unify_condition(self):+ """parent(?x, ?y) must not match a 1-argument fact."""+ self.assertIsNone(unify_condition("parent(?x, ?y)", Fact("f", "parent", ["a"])))++ def test_too_few_args_via_alpha_node(self):+ node = AlphaNode("a1", "parent(?x, ?y)")+ self.assertIsNone(node.add_fact(Fact("f", "parent", ["a"])))++ def test_too_few_args_via_rete_engine(self):+ engine = ReteEngine()+ engine.build_network(+ [+ Rule(+ rule_id="r",+ name="t",+ conditions=["parent(?x, ?y)"],+ conclusion="ok",+ )+ ]+ )+ engine.add_fact(Fact("f", "parent", ["a"]))+ self.assertEqual(engine.match_patterns(), [])++ def test_zero_arg_condition_rejects_one_arg_fact(self):+ """axiom() must not fire for a fact that carries an argument."""+ node = AlphaNode("a1", "axiom()")+ self.assertIsNone(node.add_fact(Fact("f", "axiom", ["x"])))+ engine = ReteEngine()+ engine.build_network(+ [Rule(rule_id="r", name="t", conditions=["axiom()"], conclusion="ok")]+ )+ engine.add_fact(Fact("f2", "axiom", ["x"]))+ self.assertEqual(engine.match_patterns(), [])++ # ------------------------------------------------------------------ #+ # Required valid matches (must still fire after the fix) #+ # ------------------------------------------------------------------ #++ def test_correct_arity_two_args_still_matches(self):+ """knows(?x, ?y) must still match a 2-argument fact."""+ result = unify_condition("knows(?x, ?y)", Fact("f", "knows", ["a", "b"]))+ self.assertEqual(result, {"x": "a", "y": "b"})++ def test_correct_arity_one_arg_still_matches(self):+ """person(?x) must still match a 1-argument fact."""+ result = unify_condition("person(?x)", Fact("f", "person", ["ann"]))+ self.assertEqual(result, {"x": "ann"})++ def test_correct_arity_three_args_with_literal_still_matches(self):+ """knows(Doe, John, ?y) must still match an exact 3-argument fact."""+ result = unify_condition(+ "knows(Doe, John, ?y)", Fact("f", "knows", ["Doe", "John", "x"])+ )+ self.assertEqual(result, {"y": "x"})++ def test_correct_arity_via_alpha_node(self):+ node = AlphaNode("a1", "knows(?x, ?y)")+ token = node.add_fact(Fact("f", "knows", ["a", "b"]))+ self.assertIsNotNone(token)+ self.assertEqual(token.bindings, {"x": "a", "y": "b"})++ def test_correct_arity_via_rete_engine(self):+ engine = ReteEngine()+ engine.build_network(+ [Rule(rule_id="r", name="t", conditions=["knows(?x, ?y)"], conclusion="ok")]+ )+ engine.add_fact(Fact("f", "knows", ["a", "b"]))+ matches = engine.match_patterns()+ self.assertEqual(len(matches), 1)+ self.assertEqual(matches[0].bindings, {"x": "a", "y": "b"})++ def test_zero_arg_condition_matches_zero_arg_fact(self):+ """axiom() must fire for a fact with no arguments."""+ engine = ReteEngine()+ engine.build_network(+ [+ Rule(+ rule_id="r",+ name="t",+ conditions=["axiom()"],+ conclusion="tautology",+ )+ ]+ )+ engine.add_fact(Fact("f", "axiom", []))+ self.assertEqual(len(engine.match_patterns()), 1)++ # ------------------------------------------------------------------ #+ # Edge cases that must survive the fix unchanged #+ # ------------------------------------------------------------------ #++ def test_arity_mismatch_does_not_corrupt_bindings_for_valid_fact(self):+ """A mismatched fact must not leave stale bindings that corrupt+ a subsequent valid fact's match in the same AlphaNode."""+ node = AlphaNode("a1", "knows(?x, ?y)")+ bad_fact = Fact("f1", "knows", ["only_one"]) # arity 1 — rejected+ good_fact = Fact("f2", "knows", ["alice", "bob"]) # arity 2 — accepted+ self.assertIsNone(node.add_fact(bad_fact))+ token = node.add_fact(good_fact)+ self.assertIsNotNone(token)+ self.assertEqual(token.bindings, {"x": "alice", "y": "bob"})++ def test_arity_mismatch_in_multi_condition_rule_does_not_fire(self):+ """A mismatched fact on the first condition of a multi-condition rule+ must not produce a partial match that leaks into the beta layer."""+ engine = ReteEngine()+ rule = Rule(+ rule_id="r",+ name="chain",+ conditions=["Person(?x)", "knows(?x, ?y)"],+ conclusion="met(?y)",+ )+ engine.build_network([rule])+ engine.add_fact(Fact("f1", "Person", ["alice"]))+ # This fact has 3 arguments but the condition expects 2 — must be+ # rejected before reaching the beta join.+ engine.add_fact(Fact("f2", "knows", ["alice", "bob", "carol"]))+ self.assertEqual(engine.match_patterns(), [])++ def test_arity_check_uses_fact_arguments_not_string_rendering(self):+ """A valid one-argument Fact whose rendered string contains a comma+ must not be incorrectly rejected by an arity mismatch.++ The old comma-count heuristic (``fact_str.count(',') == len(args) - 1``)+ evaluated to ``False`` for this case — the comma in the value made the+ counts disagree — so the guard was bypassed entirely, leaving the regex+ unchecked. The structural check (``_count_pattern_arity(pattern) ==+ len(fact.arguments)``) correctly sees arity 1 on both sides and lets the+ match proceed, binding ``?x`` to the full value including the comma.+ """+ fact = Fact("f", "pred", ["hello, world"]) # 1 arg, value has a comma+ result = unify_condition("pred(?x)", fact)+ self.assertIsNotNone(result)+ self.assertEqual(result, {"x": "hello, world"})+ # AlphaNode path+ node = AlphaNode("a1", "pred(?x)")+ token = node.add_fact(fact)+ self.assertIsNotNone(token)+ self.assertEqual(token.bindings, {"x": "hello, world"})++ def test_arity_check_not_fooled_by_nested_call_in_condition(self):+ """A condition whose second argument is a nested call must count as+ two top-level arguments, not more."""+ from semantica.reasoning.rete_engine import _count_pattern_arity++ # pred(?x, f(?y, ?z)) has 2 top-level args+ self.assertEqual(_count_pattern_arity("pred(?x, f(?y, ?z))"), 2)+ # A 2-arg fact matches; a 3-arg fact is rejected+ fact2 = Fact("f", "pred", ["a", "f(b, c)"])+ fact3 = Fact("f", "pred", ["a", "b", "c"])+ self.assertIsNotNone(unify_condition("pred(?x, ?y)", fact2))+ self.assertIsNone(unify_condition("pred(?x, ?y)", fact3))++if __name__ == "__main__":unittest.main()