Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Merge remote-tracking branch 'origin/main' into fix/rete-pattern-matching

KaifAhmad1f3d5932c24a7
diff --cc CHANGELOG.md
index 392921f8,71f46987..40b813de
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -108,14 -213,12 +213,21 @@@ and this project adheres to [Semantic V
### Fixed
+- **RETE engine matched every fact against every rule — `AlphaNode._matches()` and `BetaNode._can_join()` were placeholder stubs that always returned `True`** (closes #300)
+ - `semantica/reasoning/rete_engine.py` shipped a Rete network whose per-condition alpha test and cross-condition beta join were both `return True` stubs, so `match_patterns()` fired every rule for every fact regardless of predicate, arity, or shared-variable consistency
+ - New module-level `unify_condition()` reuses the regex-based approach from `Reasoner._match_pattern()`: a condition pattern like `Person(?x)` / `Parent(?x, ?y)` is compiled against a fact's `predicate(arg, ...)` string, `?var` becomes a named capture group, and a variable seen twice within one condition (e.g. `Loves(?x, ?x)`) becomes a backreference, so it only unifies when both positions hold the same value. Returns the bindings dict or `None`
+ - Reworked propagation to carry partial-match **tokens** instead of bare facts: a new `Token` dataclass bundles the accumulated `facts` with the consistent `bindings`. `AlphaNode` emits a single-fact token per match; `BetaNode.join()` merges a left token with a right token, concatenating their facts in condition order and returning the merged token only when shared variables agree (conflicting values → `None`, no join). Terminal activations carry the full fact list and accumulated bindings through to the emitted match
+ - This fixes a P1 chained-join defect: rules with three or more conditions (e.g. `Person(?x)`, `Parent(?x, ?y)`, `Located(?y, ?z)`) previously lost bindings and accumulated wrong facts at the third join, and a conflicting third condition could spuriously fire. Beta nodes now keep both `left_tokens` and `right_tokens` memories and join each new token against every token on the opposite side, so deep chains stay binding-consistent and third-level conflicts are correctly suppressed
+ - Fixed an adjacent network-topology bug surfaced by the above: newly created beta nodes were never appended to their input nodes' `children`, so tokens could not propagate; propagation was reworked to support chained joins and to thread bindings end-to-end
++ - Reconciled with the rule-actions/provenance layer (#1096) merged after this fix was opened: `execute_matches()` still dedupes and fires `Rule.actions`/legacy `handler` through a bound `Reasoner` via `_make_activation_key`, now sourced from the Token model's own `bindings` instead of the interim `_bindings_for_rule()` regex re-extraction, which is removed as redundant
+ - New `tests/reasoning/test_rete_engine.py`: `unify_condition` unit cases (single/multi variable, literal args, predicate mismatch, repeated-variable equality), alpha match/reject, beta consistent-join vs conflict-reject, end-to-end rules (single-condition fires only the matching fact; multi-condition join fires only on consistent bindings), and a `TestThreeConditionChain` suite (valid three-condition match, third-level conflict suppression, insertion-order independence, `Match.facts` complete and in condition order, multiple left tokens joining one right fact, parity against `Reasoner._match_rule()`, and `reset()` clearing all token memory)
+
+ - **KG provenance tests asserted on generated ID strings instead of stored records, and `kg_provenance.py` was missed by the `utcnow` sweep** (closes #946) by @pravit-amp
+ - The KG workflow and integration suites checked that a tracker call returned an ID matching a prefix (`assert cent_id.startswith("centrality_")`) without ever reading the record back, so an ID generator that returned a well-formed string and wrote nothing would have passed. Worse, some of those calls named tracker methods that do not exist anywhere in `semantica/` (`track_layer_analysis`, `track_centrality_score`), so the assertions were satisfied with no real interaction behind them
+ - Those tests now read provenance back through `get_provenance()` and assert on algorithm metadata, and call the methods that actually persist records. Verified by mutation rather than by a green run alone: neutering the manager's storage write (`self.storage.store(...)` → no-op) fails 10 tests
+ - `GraphBuilderWithProvenance` in `semantica/kg/kg_provenance.py` still stamped `activity_started_at_time`/`activity_ended_at_time` with the deprecated `datetime.utcnow()`; it was outside the `export/`+`provenance/` scope of the #1114 sweep below and now uses the same `utc_now_iso()` helper. `docs/guides/provenance.md` and `docs/reference/provenance.md` were still documenting `utcnow()` and a naive timestamp example, and now show the helper and the offset-bearing form
+ - 16 tests across the affected suites ended in `return <value>` instead of asserting, which pytest reports as `PytestReturnNotNoneWarning`; now zero
+
- **The temporal-evolution `stability` metric was a hardcoded placeholder, not a duration**
- `TemporalGraphQuery.analyze_evolution()` documents `stability` as a "relationship duration/stability measure", but the implementation appended a constant `1` for every relationship with both `valid_from` and `valid_until` set (`durations.append(1) # Placeholder`). The reported stability was therefore always `1.0` when any bounded relationship existed and `0` otherwise — it never reflected how long relationships actually stayed valid, so it could not distinguish a graph of decade-long relationships from one of one-second relationships
- `stability` now computes the mean valid-time duration in seconds (`(valid_until - valid_from).total_seconds()`) across relationships that have both bounds set. Relationships with a missing or open `valid_from`/`valid_until` are skipped (their duration is unbounded), and non-positive intervals are clamped to `0`; an empty set still reports `0`
diff --cc semantica/reasoning/rete_engine.py
index 59e0514f,8fe9b7d3..68551de1
--- a/semantica/reasoning/rete_engine.py
+++ b/semantica/reasoning/rete_engine.py
@@@ -39,33 -39,27 +39,33 @@@ from typing import Any, Dict, List, Opt
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
- from .reasoner import Fact, Rule
+ from .reasoner import Fact, Rule, _make_activation_key
+logger = get_logger("rete_engine")
-def _extract_bindings(condition: Any, fact: Fact) -> Dict[str, Any]:
- """Extract ``?var`` bindings by matching a condition pattern against a fact.
- ``condition`` is the pattern stored on the alpha node (typically a string
- like ``"Person(?x)"``); ``fact`` is the working-memory :class:`Fact`. The
- fact's canonical string form (``Predicate(arg1, arg2, ...)``) is matched
- against the pattern using the same ``?\\w+`` placeholder convention as the
- Reasoner, so downstream actions receive real bindings (e.g. ``{"x": "John"}``)
- instead of the empty dict that previously left ``?x`` placeholders
- unsubstituted.
+def _build_condition_regex(
+ pattern: str,
+ initial_bindings: Optional[Dict[str, str]] = None,
+) -> str:
+ """Build an anchored regex string for a condition pattern.
- Returns an empty dict when the condition is not a string pattern or does
- not match -- callers treat that as "no bindings extracted".
- """
- if not isinstance(condition, str):
- return {}
+ Splits the pattern on ``?var`` placeholders, escaping the literal
+ segments so surrounding parentheses/commas match literally. Variables
+ become named groups (or backreferences when repeated); variables already
+ present in ``initial_bindings`` are inlined as their literal value.
+
+ Args:
+ pattern: The condition pattern string (e.g. ``"Person(?x)"``).
+ initial_bindings: Bindings already established upstream. Variables
+ already bound are matched as literals rather than captured.
- segments = re.split(r"(\?\w+)", condition)
+ Returns:
+ An anchored regex string (``^...$``) suitable for ``re.compile`` /
+ ``re.match``.
+ """
+ bindings = initial_bindings or {}
+ segments = re.split(r"(\?\w+)", pattern)
seen_vars: Set[str] = set()
p_regex = ""
for seg in segments:
@@@ -578,15 -459,17 +608,20 @@@ class ReteEngine
)
raise
+ def reset_action_history(self) -> None:
+ """Allow previously executed activations to fire their actions again."""
+ self._executed_activations.clear()
+
def reset(self) -> None:
- """Reset Rete engine."""
+ """Reset Rete working memory and action activation history."""
self.facts.clear()
+ self.reset_action_history()
for node in self.network.values():
- if isinstance(node, AlphaNode) or isinstance(node, BetaNode):
- node.matches.clear()
+ if isinstance(node, AlphaNode):
+ node.tokens.clear()
+ elif isinstance(node, BetaNode):
+ node.left_tokens.clear()
+ node.right_tokens.clear()
elif isinstance(node, TerminalNode):
node.activations.clear()
diff --cc tests/reasoning/test_rete_engine.py
index d6ef29a4,00000000..cc43e9c6
mode 100644,000000..100644
--- a/tests/reasoning/test_rete_engine.py
+++ b/tests/reasoning/test_rete_engine.py
@@@ -1,366 -1,0 +1,366 @@@
+"""Tests for the RETE engine pattern matching (issue #300).
+
+These tests verify that ``AlphaNode._matches`` and ``BetaNode._can_join`` no
+longer behave like the old always-``True`` stubs, and that the network as a
+whole only fires rules whose conditions actually unify with the facts.
+"""
+
+import itertools
+import re
+import unittest
+from unittest import mock
+
+from semantica.reasoning import rete_engine
+from semantica.reasoning.reasoner import Fact, Rule
+from semantica.reasoning.rete_engine import (
+ AlphaNode,
+ BetaNode,
+ ReteEngine,
+ unify_condition,
+)
+
+
+class TestUnifyCondition(unittest.TestCase):
+ def test_single_variable_binds(self):
+ fact = Fact("f1", "Person", ["John"])
+ bindings = unify_condition("Person(?x)", fact)
+ self.assertEqual(bindings, {"x": "John"})
+
+ def test_predicate_mismatch_returns_none(self):
+ fact = Fact("f1", "Company", ["Google"])
+ self.assertIsNone(unify_condition("Person(?x)", fact))
+
+ def test_two_arguments_bind(self):
+ fact = Fact("f2", "Parent", ["John", "Mary"])
+ bindings = unify_condition("Parent(?x, ?y)", fact)
+ self.assertEqual(bindings, {"x": "John", "y": "Mary"})
+
+ def test_literal_argument_must_match(self):
+ fact = Fact("f3", "Parent", ["John", "Mary"])
+ self.assertIsNone(unify_condition("Parent(Bob, ?y)", fact))
+ self.assertEqual(unify_condition("Parent(John, ?y)", fact), {"y": "Mary"})
+
+ def test_repeated_variable_requires_equal_values(self):
+ loves_self = Fact("f4", "Loves", ["John", "John"])
+ loves_other = Fact("f5", "Loves", ["John", "Mary"])
+ self.assertEqual(unify_condition("Loves(?x, ?x)", loves_self), {"x": "John"})
+ self.assertIsNone(unify_condition("Loves(?x, ?x)", loves_other))
+
+ 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:
+ result = unify_condition("Person(?x)", fact)
+ self.assertIsNone(result)
+ joined = "\n".join(captured.output)
+ self.assertIn("Person(?x)", joined)
+ self.assertIn("Person(John)", joined)
+ self.assertIn("bad pattern", joined)
+
+ 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:
+ result = unify_condition("Person(?x)", fact)
+ self.assertIsNone(result)
+ self.assertIn("boom", "\n".join(captured.output))
+
+
+class TestAlphaNode(unittest.TestCase):
+ def test_matches_stores_bindings(self):
+ node = AlphaNode("a1", "Person(?x)")
+ fact = Fact("f1", "Person", ["John"])
+ token = node.add_fact(fact)
+ self.assertIsNotNone(token)
+ assert token is not None # narrow type for the checker
+ self.assertEqual(token.facts, [fact])
+ self.assertEqual(token.bindings, {"x": "John"})
+ self.assertIn(token, node.tokens)
+
+ def test_non_matching_fact_rejected(self):
+ node = AlphaNode("a1", "Person(?x)")
+ fact = Fact("f1", "Company", ["Google"])
+ self.assertIsNone(node.add_fact(fact))
+ self.assertEqual(node.tokens, [])
+
+ def test_uses_precompiled_regex(self):
+ """AlphaNode compiles its condition once and reuses it per fact."""
+ node = AlphaNode("a1", "Person(?x)")
+ self.assertIsNotNone(node._compiled)
+ # Matching goes through the compiled matcher, not unify_condition.
+ with mock.patch.object(rete_engine, "unify_condition") as unify:
+ fact = Fact("f1", "Person", ["John"])
+ token = node.add_fact(fact)
+ unify.assert_not_called()
+ self.assertIsNotNone(token)
+ assert token is not None
+ self.assertEqual(token.bindings, {"x": "John"})
+
+ 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:
+ node = AlphaNode("bad", "Person(?x)")
+ self.assertIsNone(node._compiled)
+ self.assertIn("failed to compile", "\n".join(captured.output))
+ fact = Fact("f1", "Person", ["John"])
+ self.assertIsNone(node.add_fact(fact))
+ self.assertEqual(node.tokens, [])
+
+
+class TestBetaNode(unittest.TestCase):
+ def test_join_consistent_bindings(self):
+ left = AlphaNode("a1", "Parent(?x, ?y)")
+ right = AlphaNode("a2", "Person(?x)")
+ beta = BetaNode("b1", left, right)
+
+ parent = Fact("f1", "Parent", ["John", "Mary"])
+ person = Fact("f2", "Person", ["John"])
+ left_token = left.add_fact(parent)
+ right_token = right.add_fact(person)
+ assert left_token is not None and right_token is not None
+
+ merged = beta.join(left_token, right_token)
+ self.assertIsNotNone(merged)
+ assert merged is not None # narrow type for the checker
+ self.assertEqual(merged.bindings, {"x": "John", "y": "Mary"})
+ # Facts are concatenated left-then-right in condition order.
+ self.assertEqual(merged.facts, [parent, person])
+
+ def test_join_conflicting_bindings_rejected(self):
+ left = AlphaNode("a1", "Parent(?x, ?y)")
+ right = AlphaNode("a2", "Person(?x)")
+ beta = BetaNode("b1", left, right)
+
+ parent = Fact("f1", "Parent", ["John", "Mary"])
+ # ?x conflicts: John vs Alice
+ person = Fact("f2", "Person", ["Alice"])
+ left_token = left.add_fact(parent)
+ right_token = right.add_fact(person)
+ assert left_token is not None and right_token is not None
+
+ self.assertIsNone(beta.join(left_token, right_token))
+
+
+class TestReteEngineEndToEnd(unittest.TestCase):
+ def test_only_matching_rule_fires(self):
+ engine = ReteEngine()
+ rule = Rule(
+ rule_id="r1",
+ name="person rule",
+ conditions=["Person(?x)"],
+ conclusion="Mortal(?x)",
+ )
+ engine.build_network([rule])
+
+ engine.add_fact(Fact("f1", "Person", ["John"]))
+ engine.add_fact(Fact("f2", "Company", ["Google"])) # should NOT fire
+
+ matches = engine.match_patterns()
+ self.assertEqual(len(matches), 1)
+ self.assertEqual(matches[0].bindings, {"x": "John"})
+
+ def test_multi_condition_join(self):
+ engine = ReteEngine()
+ rule = Rule(
+ rule_id="r1",
+ name="child rule",
+ conditions=["Person(?x)", "Parent(?x, ?y)"],
+ conclusion="Child(?y, ?x)",
+ )
+ engine.build_network([rule])
+
+ engine.add_fact(Fact("f1", "Person", ["John"]))
+ engine.add_fact(Fact("f2", "Parent", ["John", "Mary"]))
+ # Unrelated parent whose ?x does not match any Person -> no activation.
+ engine.add_fact(Fact("f3", "Parent", ["Bob", "Sue"]))
+
+ matches = engine.match_patterns()
+ self.assertEqual(len(matches), 1)
+ self.assertEqual(matches[0].bindings, {"x": "John", "y": "Mary"})
+
+ def test_no_activation_when_join_inconsistent(self):
+ engine = ReteEngine()
+ rule = Rule(
+ rule_id="r1",
+ name="child rule",
+ conditions=["Person(?x)", "Parent(?x, ?y)"],
+ conclusion="Child(?y, ?x)",
+ )
+ engine.build_network([rule])
+
+ engine.add_fact(Fact("f1", "Person", ["John"]))
+ engine.add_fact(Fact("f2", "Parent", ["Alice", "Mary"])) # ?x mismatch
+
+ matches = engine.match_patterns()
+ self.assertEqual(matches, [])
+
+
+class TestThreeConditionChain(unittest.TestCase):
+ """Chained beta joins across three or more conditions (issue #300).
+
+ These exercise the Token model: a token must accumulate the ordered
+ facts and the consistent bindings of every condition, so that deep
+ chains neither drop bindings nor duplicate facts, and a conflict on the
+ third condition correctly suppresses activation.
+ """
+
+ def _three_condition_rule(self):
+ return Rule(
+ rule_id="r1",
+ name="location chain",
+ conditions=[
+ "Person(?x)",
+ "Parent(?x, ?y)",
+ "Located(?y, ?z)",
+ ],
+ conclusion="LivesNear(?x, ?z)",
+ )
+
+ def test_three_condition_valid_match(self):
+ engine = ReteEngine()
+ engine.build_network([self._three_condition_rule()])
+
+ engine.add_fact(Fact("f1", "Person", ["John"]))
+ engine.add_fact(Fact("f2", "Parent", ["John", "Mary"]))
+ engine.add_fact(Fact("f3", "Located", ["Mary", "Paris"]))
+
+ matches = engine.match_patterns()
+ self.assertEqual(len(matches), 1)
+ self.assertEqual(
+ matches[0].bindings,
+ {"x": "John", "y": "Mary", "z": "Paris"},
+ )
+
+ def test_three_condition_third_level_conflict(self):
+ engine = ReteEngine()
+ engine.build_network([self._three_condition_rule()])
+
+ engine.add_fact(Fact("f1", "Person", ["John"]))
+ engine.add_fact(Fact("f2", "Parent", ["John", "Mary"]))
+ # ?y is bound to Mary, so a Located fact about Bob must not join.
+ engine.add_fact(Fact("f3", "Located", ["Bob", "Paris"]))
+
+ matches = engine.match_patterns()
+ self.assertEqual(matches, [])
+
+ def test_fact_insertion_order_independent(self):
+ # Whatever order facts arrive, the same single match must result.
+ base_facts = [
+ Fact("f1", "Person", ["John"]),
+ Fact("f2", "Parent", ["John", "Mary"]),
+ Fact("f3", "Located", ["Mary", "Paris"]),
+ ]
+ expected = {"x": "John", "y": "Mary", "z": "Paris"}
+
+ for order in itertools.permutations(base_facts):
+ engine = ReteEngine()
+ engine.build_network([self._three_condition_rule()])
+ for fact in order:
+ engine.add_fact(fact)
+ matches = engine.match_patterns()
+ self.assertEqual(len(matches), 1, f"order={order}")
+ self.assertEqual(matches[0].bindings, expected)
+
+ def test_match_facts_complete_in_condition_order(self):
+ engine = ReteEngine()
+ engine.build_network([self._three_condition_rule()])
+
+ person = Fact("f1", "Person", ["John"])
+ parent = Fact("f2", "Parent", ["John", "Mary"])
+ located = Fact("f3", "Located", ["Mary", "Paris"])
+ engine.add_fact(person)
+ engine.add_fact(parent)
+ engine.add_fact(located)
+
+ matches = engine.match_patterns()
+ self.assertEqual(len(matches), 1)
+ # All three facts preserved, in condition order, no duplicates.
+ self.assertEqual(matches[0].facts, [person, parent, located])
+
+ def test_multiple_left_tokens_join_one_right_fact(self):
+ # Two Person/Parent chains sharing the same Located(?y, ?z) fact.
+ engine = ReteEngine()
+ engine.build_network([self._three_condition_rule()])
+
+ engine.add_fact(Fact("f1", "Person", ["John"]))
+ engine.add_fact(Fact("f2", "Parent", ["John", "Mary"]))
+ engine.add_fact(Fact("f3", "Person", ["Alice"]))
+ engine.add_fact(Fact("f4", "Parent", ["Alice", "Mary"]))
+ # One right fact should join with both accumulated left tokens.
+ engine.add_fact(Fact("f5", "Located", ["Mary", "Paris"]))
+
+ matches = engine.match_patterns()
+ self.assertEqual(len(matches), 2)
+ result = {m.bindings["x"]: m.bindings["z"] for m in matches}
+ self.assertEqual(result, {"John": "Paris", "Alice": "Paris"})
+
+ def test_matches_reasoner_match_rule(self):
+ from semantica.reasoning.reasoner import Reasoner
+
+ rule = self._three_condition_rule()
+ facts = [
+ Fact("f1", "Person", ["John"]),
+ Fact("f2", "Parent", ["John", "Mary"]),
+ Fact("f3", "Located", ["Mary", "Paris"]),
+ ]
+
+ # Reasoner works over stringified facts and returns
- # (conclusion, matched_facts) tuples from self.facts.
++ # (conclusion, matched_facts, bindings) tuples from self.facts.
+ reasoner = Reasoner()
+ for fact in facts:
+ reasoner.add_fact(str(fact))
+ reasoner_matches = reasoner._match_rule(rule)
+
+ engine = ReteEngine()
+ engine.build_network([rule])
+ for fact in facts:
+ engine.add_fact(fact)
+ rete_matches = engine.match_patterns()
+
+ # Both engines must agree on the number of activations.
+ self.assertEqual(len(rete_matches), len(reasoner_matches))
+ self.assertEqual(len(rete_matches), 1)
+ self.assertEqual(
+ rete_matches[0].bindings,
+ {"x": "John", "y": "Mary", "z": "Paris"},
+ )
+ # The RETE match must carry the instantiated conclusion facts too.
- conclusion, _ = reasoner_matches[0]
++ conclusion, _, _ = reasoner_matches[0]
+ self.assertEqual(conclusion, "LivesNear(John, Paris)")
+
+ def test_reset_clears_all_token_memory(self):
+ engine = ReteEngine()
+ engine.build_network([self._three_condition_rule()])
+
+ engine.add_fact(Fact("f1", "Person", ["John"]))
+ engine.add_fact(Fact("f2", "Parent", ["John", "Mary"]))
+ engine.add_fact(Fact("f3", "Located", ["Mary", "Paris"]))
+ self.assertEqual(len(engine.match_patterns()), 1)
+
+ engine.reset()
+
+ # No stale facts, tokens or activations remain anywhere.
+ self.assertEqual(engine.facts, [])
+ for node in engine.network.values():
+ if isinstance(node, AlphaNode):
+ self.assertEqual(node.tokens, [])
+ elif isinstance(node, BetaNode):
+ self.assertEqual(node.left_tokens, [])
+ self.assertEqual(node.right_tokens, [])
+ self.assertEqual(engine.match_patterns(), [])
+
+
+if __name__ == "__main__":
+ unittest.main()