Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(reasoning): add source-aware truth maintenance for non-recursive rules (#1544)

cxzg00792c2578a142a
diff --git a/docs/docs.json b/docs/docs.json
index f36fffa5..4c9aa69c 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -204,6 +204,7 @@
"reference/distance",
"reference/semantic_extract",
"reference/reasoning",
+ "reference/truth_maintenance",
"reference/ontology"
]
},
diff --git a/docs/reference/reasoning.md b/docs/reference/reasoning.md
index c56b5301..88832e0e 100644
--- a/docs/reference/reasoning.md
+++ b/docs/reference/reasoning.md
@@ -483,6 +483,7 @@ step.confidence # float
</Warning>
- [Knowledge Graph](/reference/kg) — The knowledge graph being reasoned over.
+- [Truth Maintenance](/reference/truth_maintenance) — Source-aware logical retraction for fixed non-recursive rules.
- [Ontology](/reference/ontology) — Ontology axioms and SHACL constraints for logical reasoning.
- [Triplet Store](/reference/triplet_store) — RDF backend for SPARQL-based reasoning.
- [Context](/reference/context) — Reasoning integrated into agent decision intelligence.
diff --git a/docs/reference/truth_maintenance.md b/docs/reference/truth_maintenance.md
new file mode 100644
index 00000000..4295768f
--- /dev/null
+++ b/docs/reference/truth_maintenance.md
@@ -0,0 +1,141 @@
+---
+title: "Truth Maintenance"
+description: "Source-aware logical retraction for fixed non-recursive rules."
+icon: "microchip"
+---
+
+`TruthMaintenanceSession` keeps derived facts synchronized with changing external evidence. It maintains the invariant:
+
+```text
+session.facts == closure(fixed_rules, facts_with_remaining_external_support)
+```
+
+Retracting a source invalidates conclusions that have lost their premises, while conclusions that still have alternative derivations or explicit support are kept.
+
+This is an **opt-in** session: the existing `Reasoner`, actions, RETE, and Datalog behavior is unchanged.
+
+
+## When to Use It
+
+Use `TruthMaintenanceSession` when:
+
+- Facts come from external evidence that can be **corrected or withdrawn** (e.g. a document revision replaces one assertion with another).
+- You need derived conclusions to be removed **only when they lose all support**, not on any deletion.
+- You want a batch update that publishes the final state and **net changes**, instead of replaying intermediate states.
+- You are hitting the limits of `RetractAction`: it removes only the requested fact and leaves unsupported conclusions behind, while a naive deletion cascade would wrongly remove conclusions that still have alternative derivations or explicit support.
+
+Do not use it for recursive rules, temporal validity, external side effects, or multi-threaded access — see [Limitations](#limitations).
+
+
+## Getting Started
+
+```python
+from semantica.reasoning import FactSupport, Rule, TruthMaintenanceSession
+
+rules = [
+ Rule(
+ rule_id="employment-eligibility",
+ name="Employment eligibility",
+ conditions=["Employed(?x)"],
+ conclusion="Eligible(?x)",
+ ),
+]
+session = TruthMaintenanceSession(rules=rules)
+
+session.apply(assertions=[
+ FactSupport(support_id="document-v1", fact="Employed(Alice)"),
+])
+
+delta = session.apply(
+ assertions=[FactSupport("document-v2", "Employed(Alice)")],
+ retractions=["document-v1"],
+)
+assert not delta.added_facts
+assert not delta.removed_facts
+assert session.explain("Eligible(Alice)").active
+
+delta = session.apply(retractions=["document-v2"])
+assert delta.removed_facts == frozenset({
+ "Employed(Alice)", "Eligible(Alice)",
+})
+```
+
+The example above is **source replacement**: swapping one supporting document for another in a single batch produces no net fact deletion or insertion, because `Employed(Alice)` remains supported and `Eligible(Alice)` keeps its derivation.
+
+
+## Core Concepts
+
+- **Support**: an external fact assertion, identified by a caller-provided `support_id`. A support ID is permanently bound to one fact for the session lifetime; withdrawing and later reactivating the same association is allowed, but binding the same ID to a different fact raises `ValidationError`.
+- **Derivation**: a rule application with rule identity, ordered premises, variable bindings, and conclusion. Independent derivations of the same conclusion are all retained; duplicate matches cannot inflate support.
+- **Version**: a monotonic commit counter. It increments once per batch that changes the support set (even if the fact set is unchanged) and stays unchanged for no-ops.
+- **Truth semantics**: losing all support means "not currently derivable", not "logically false".
+
+
+## Session API
+
+### `TruthMaintenanceSession(rules=...)`
+
+Constructs the session from an iterable of existing [`Rule`](/reference/reasoning#rule-and-fact-dataclass-fields) objects. The rules are copied into immutable internal snapshots: later mutation of the original `Rule` objects does not affect the session.
+
+The rule set must be:
+
+- **Positive, function-free implications** with at least one body atom.
+- **Range-restricted**: every head variable occurs in the body.
+- **Acyclic**: the predicate dependency graph must not contain direct or indirect recursion; cyclic rule sets are rejected at construction.
+- **Side-effect free**: actions, handlers, and non-implication rule types are rejected; `confidence` must be `1.0`.
+
+### `apply(assertions=..., retractions=...)`
+
+Atomically applies one batch:
+
+- `assertions`: iterable of `FactSupport`.
+- `retractions`: iterable of support-ID strings.
+
+Returns a `MaintenanceDelta` with `version`, `added_facts`, `removed_facts`, `added_supports`, and `removed_supports` (net values, observed after commit).
+
+Validation and error semantics:
+
+- Re-asserting an already active support with the same fact is a no-op; retracting an unknown or inactive support is a no-op.
+- A support ID bound to a different fact, the same ID in both assertions and retractions of one batch, or any malformed input raises the existing `ValidationError`.
+- Unexpected internal failures raise `ProcessingError` with the original cause attached.
+- **Any failed batch leaves the committed facts, support catalog, derivations, and version unchanged.**
+
+### `explain(fact)`
+
+Returns a `FactExplanation` for the current state:
+
+- `fact`: the canonical fact string.
+- `active`: whether the fact currently holds.
+- `explicit_support_ids`: sorted IDs of external supports.
+- `derivations`: all retained direct derivations (rule ID, ordered premises, bindings).
+
+### Read-only views
+
+- `facts`: frozenset of all currently believed facts (explicit plus derived).
+- `version`: the commit counter described above.
+
+Returned snapshots (`MaintenanceDelta`, `FactExplanation`, `Derivation`) are frozen dataclasses with immutable collections; mutating caller-owned rules or previously returned results cannot mutate the session.
+
+
+## Cost Model
+
+- **Deletion propagation** and **affected-rule matching** are incremental: a deletion-only batch uses dependency indexes without rescanning all rules; insertions reevaluate only rules reachable from newly active predicates.
+- **Staging copies the whole session state** per `apply()` batch to guarantee atomic commits, and the session retains the **support catalog in memory** for the session lifetime (including withdrawn supports, so IDs stay bound).
+- The copy-on-update and catalog costs are per-batch whole-state costs; do not assume end-to-end latency is strictly proportional to the affected subgraph. Measure before relying on performance.
+
+
+## Limitations
+
+- **Non-recursive rules only**; the constructor rejects cyclic predicate dependencies.
+- **Narrow atom syntax**: ASCII predicate/variable identifiers and unquoted scalar symbol constants, including zero-arity atoms. No quoted strings, whitespace-bearing constants, nested terms, comparisons, aggregation, negation, or disjunction. Exactly one arity per predicate within the session.
+- **Boolean support semantics**; no confidence propagation, no probabilistic reasoning.
+- **No side effects**: the session never executes actions or handlers and creates no LLM or store clients.
+- **No thread-safety, persistence, temporal validity, or cross-store synchronization** guarantees. Access must be caller-serialized in a single process.
+- **Fixed rules**: rule changes require constructing a new session.
+- No historical proof archive: `explain()` describes the current state only.
+
+
+## Links
+
+- [Reasoning](/reference/reasoning) — the rule engines this session builds on, including the `Rule` representation.
+- [Ontology](/reference/ontology) — ontology axioms and SHACL constraints.
diff --git a/semantica/reasoning/__init__.py b/semantica/reasoning/__init__.py
index 00a71576..5893e3d8 100644
--- a/semantica/reasoning/__init__.py
+++ b/semantica/reasoning/__init__.py
@@ -7,15 +7,7 @@ rule-based inference via Rete, SPARQL reasoning, abductive and deductive reasoni
and native Datalog evaluation.
"""
-from .reasoner import Reasoner, InferenceResult, Rule, Fact, RuleType
-from .reasoner import (
- Action,
- AssertAction,
- RetractAction,
- CallAction,
- EmitEventAction,
-)
-from .graph_reasoner import GraphReasoner
+from .datalog_reasoner import DatalogFact, DatalogReasoner, DatalogRule
from .explanation_generator import (
Explanation,
ExplanationGenerator,
@@ -23,6 +15,19 @@ from .explanation_generator import (
ReasoningPath,
ReasoningStep,
)
+from .graph_reasoner import GraphReasoner
+from .reasoner import (
+ Action,
+ AssertAction,
+ CallAction,
+ EmitEventAction,
+ Fact,
+ InferenceResult,
+ Reasoner,
+ RetractAction,
+ Rule,
+ RuleType,
+)
from .rete_engine import (
AlphaNode,
BetaNode,
@@ -32,9 +37,18 @@ from .rete_engine import (
TerminalNode,
)
from .sparql_reasoner import SPARQLQueryResult, SPARQLReasoner
-
-from .datalog_reasoner import DatalogReasoner, DatalogFact, DatalogRule
-from .temporal_reasoning import IntervalRelation, TemporalInterval, TemporalReasoningEngine
+from .temporal_reasoning import (
+ IntervalRelation,
+ TemporalInterval,
+ TemporalReasoningEngine,
+)
+from .truth_maintenance import TruthMaintenanceSession
+from .truth_maintenance_types import (
+ Derivation,
+ FactExplanation,
+ FactSupport,
+ MaintenanceDelta,
+)
__all__ = [
# Reasoner facade
@@ -67,6 +81,12 @@ __all__ = [
"TemporalInterval",
"IntervalRelation",
"TemporalReasoningEngine",
+ # Truth maintenance
+ "TruthMaintenanceSession",
+ "FactSupport",
+ "Derivation",
+ "FactExplanation",
+ "MaintenanceDelta",
# Explanation
"ExplanationGenerator",
"Explanation",
diff --git a/semantica/reasoning/_rule_matching.py b/semantica/reasoning/_rule_matching.py
new file mode 100644
index 00000000..2fdfce66
--- /dev/null
+++ b/semantica/reasoning/_rule_matching.py
@@ -0,0 +1,148 @@
+"""Pure rule-matching helpers shared by the Reasoner and newer engines.
+
+This module extracts the variable substitution and pattern matching logic
+that used to live inside ``Reasoner`` so that other components (for example
+the truth maintenance session) can reuse the exact same matching semantics
+without instantiating a ``Reasoner`` (and therefore without inheriting its
+actions, activation deduplication, or iteration limits).
+
+The functions here are intentionally free of framework state: logging is
+performed through an explicit ``logger`` argument, and rule evaluation takes
+the facts and the substitution callables as arguments. Behavior is identical
+to the previous in-class implementation.
+"""
+
+import re
+from collections.abc import Iterable
+from typing import Callable, Dict, List, Optional, Tuple
+
+PatternMatcher = Callable[[str, str, Dict[str, str]], Optional[Dict[str, str]]]
+Substituter = Callable[[str, Dict[str, str]], str]
+
+
+def substitute_variables(template: str, bindings: Dict[str, str]) -> str:
+ """Substitute ``?var`` placeholders with their bound values, token-aware.
+
+ A naive ``str.replace(f"?{var}", value)`` corrupts placeholders that share
+ a prefix -- e.g. binding ``?x`` would also rewrite the ``?x`` inside ``?xy``.
+ We replace every ``?word`` token in a single regex pass so that only whole
+ variable names are matched (``\\w+`` never partially matches a longer name),
+ leaving unbound placeholders untouched.
+ """
+ if not bindings:
+ return template
+
+ def _replace(match: "re.Match") -> str:
+ var_name = match.group(1)
+ # Preserve unbound placeholders verbatim.
+ return str(bindings[var_name]) if var_name in bindings else match.group(0)
+
+ return re.sub(r"\?(\w+)", _replace, template)
+
+
+def match_pattern(
+ pattern: str,
+ fact: str,
+ initial_bindings: Dict[str, str],
+ *,
+ logger=None,
+) -> Optional[Dict[str, str]]:
+ """Match a pattern against a fact with initial bindings.
+
+ Variables already present in ``initial_bindings`` must match their bound
+ value exactly; a variable that occurs multiple times in the pattern must
+ bind the same value each time (enforced through a regex backreference).
+ Returns the extended bindings on success or ``None`` when the fact does
+ not match. Unexpected failures are logged through ``logger`` (if given)
+ and also result in ``None``.
+ """
+ # Split on ?var placeholders first, then escape only the literal segments.
+ # This avoids re.escape() mangling the surrounding parentheses and ?
+ # before the variable substitution step.
+ segments = re.split(r"(\?\w+)", pattern)
+ seen_vars: set = set()
+ p_regex = ""
+ for seg in segments:
+ if seg.startswith("?"):
+ var_name = seg[1:]
+ if var_name in initial_bindings:
+ # Already bound — require the exact literal value
+ p_regex += re.escape(initial_bindings[var_name])
+ elif var_name in seen_vars:
+ # Same variable used twice — use a backreference
+ p_regex += f"(?P={var_name})"
+ else:
+ p_regex += f"(?P<{var_name}>.+?)"
+ seen_vars.add(var_name)
+ else:
+ p_regex += re.escape(seg)
+ p_regex = f"^{p_regex}$"
+
+ # Simple regex-based matcher for patterns like "Person(?x)" and facts like "Person(John)"
+
+ try:
+ match = re.match(p_regex, fact)
+ if match:
+ new_bindings = initial_bindings.copy()
+ for var, value in match.groupdict().items():
+ if var in new_bindings and new_bindings[var] != value:
+ return None # Binding conflict
+ new_bindings[var] = value
+ return new_bindings
+ except Exception as e: # pragma: no cover - defensive, mirrors legacy behavior
+ if logger is not None:
+ logger.warning(
+ f"Error matching pattern '{pattern}' (regex: '{p_regex}') "
+ f"against fact '{fact}': {e}"
+ )
+
+ return None
+
+
+def match_rule(
+ conditions: List[str],
+ conclusion: str,
+ facts: Iterable[str],
+ *,
+ pattern_matcher: PatternMatcher,
+ substituter: Substituter,
+) -> List[Tuple[str, List[str], Dict[str, str]]]:
+ """Match rule conditions against facts and return instantiated conclusions.
+
+ Returns a list of ``(conclusion, matched_facts, bindings)`` tuples where
+ ``matched_facts`` is the ordered list of facts bound to the conditions and
+ ``bindings`` maps variable name -> matched value. Rules without conditions
+ never match.
+ """
+ if not conditions:
+ return []
+
+ # ``facts`` is not mutated anywhere within this function, so sort it once
+ # here rather than re-sorting on every (bindings, condition) pair below --
+ # sorted() was previously called once per inner-loop entry, which
+ # re-allocates and re-sorts the full fact set repeatedly and is a hot spot
+ # for larger fact sets.
+ sorted_facts = sorted(facts)
+
+ # Each entry pairs a set of variable bindings with the facts that were
+ # matched to produce those bindings, so the facts survive alongside the
+ # bindings as conditions accumulate.
+ bindings_list: List[Tuple[Dict[str, str], List[str]]] = [({}, [])]
+
+ for condition in conditions:
+ new_bindings_list = []
+ for bindings, matched_facts in bindings_list:
+ for fact in sorted_facts:
+ match_bindings = pattern_matcher(condition, fact, bindings)
+ if match_bindings is not None:
+ new_bindings_list.append((match_bindings, matched_facts + [fact]))
+ bindings_list = new_bindings_list
+ if not bindings_list:
+ break
+
+ results = []
+ for bindings, matched_facts in bindings_list:
+ instantiated_conclusion = substituter(conclusion, bindings)
+ results.append((instantiated_conclusion, matched_facts, bindings))
+
+ return results
\ No newline at end of file
diff --git a/semantica/reasoning/_truth_maintenance_validation.py b/semantica/reasoning/_truth_maintenance_validation.py
new file mode 100644
index 00000000..f2dede66
--- /dev/null
+++ b/semantica/reasoning/_truth_maintenance_validation.py
@@ -0,0 +1,273 @@
+"""Internal validation and parsing helpers for truth maintenance.
+
+Grammar::
+
+ identifier := [A-Za-z_][A-Za-z0-9_]*
+ variable := '?' identifier
+ constant := [A-Za-z0-9_][A-Za-z0-9_./:#-]*
+ atom := identifier '(' [term (',' term)*] ')'
+
+Whitespace between tokens is normalized to the canonical form ``P(a, b)``.
+Everything in this module is pure: it neither touches session state nor
+invokes the rule matcher.
+"""
+
+import re
+from collections.abc import Iterable
+from typing import Dict, List, Optional, Set, Tuple
+
+from semantica.utils.exceptions import ValidationError
+
+from .reasoner import Rule, RuleType
+from .truth_maintenance_types import _RuleSnapshot
+
+_IDENTIFIER = r"[A-Za-z_][A-Za-z0-9_]*"
+_VARIABLE = r"\?" + _IDENTIFIER
+_CONSTANT = r"[A-Za-z0-9_][A-Za-z0-9_./:#-]*"
+
+_ATOM_RE = re.compile(
+ r"^(?P<predicate>" + _IDENTIFIER + r")\s*\((?P<args>.*)\)$",
+ re.DOTALL,
+)
+_TERM_RE = re.compile(r"^(" + _VARIABLE + r"|" + _CONSTANT + r")$")
+_VARIABLE_RE = re.compile(r"^" + _VARIABLE + r"$")
+
+
+def _fail(message: str, **details: object) -> ValidationError:
+ return ValidationError(message, validation_context=dict(details))
+
+
+def parse_atom(text: object) -> Tuple[str, Tuple[str, ...]]:
+ """Parse and normalize an atom string.
+
+ Returns ``(predicate, terms)`` where each term is a variable (leading
+ ``?``) or a constant. Raises ``ValidationError`` on any syntax error.
+ """
+ if not isinstance(text, str):
+ raise _fail("atom must be a string", atom=repr(text))
+ stripped = text.strip()
+ match = _ATOM_RE.match(stripped)
+ if match is None:
+ raise _fail("atom must look like P(a, b)", atom=text)
+ predicate = match.group("predicate")
+ raw_args = match.group("args").strip()
+ terms: List[str] = []
+ if raw_args:
+ for raw_term in raw_args.split(","):
+ term = raw_term.strip()
+ if not _TERM_RE.match(term):
+ raise _fail(
+ "atom argument must be a variable or constant",
+ atom=text,
+ argument=raw_term.strip(),
+ )
+ terms.append(term)
+ return predicate, tuple(terms)
+
+
+def normalize_atom(text: object) -> str:
+ """Return the canonical whitespace-normalized form of an atom."""
+ predicate, terms = parse_atom(text)
+ return canonical_atom(predicate, terms)
+
+
+def canonical_atom(predicate: str, terms: Iterable[str]) -> str:
+ return predicate + "(" + ", ".join(terms) + ")"
+
+
+def _is_variable(term: str) -> bool:
+ return _VARIABLE_RE.match(term) is not None
+
+
+def validate_fact_text(text: object) -> str:
+ """Validate a fact atom: constant arguments only. Returns canonical form."""
+ predicate, terms = parse_atom(text)
+ for term in terms:
+ if _is_variable(term):
+ raise _fail(
+ "fact arguments must be constants, not variables",
+ fact=text,
+ )
+ return canonical_atom(predicate, terms)
+
+
+def _validate_rule_shape(rule: object, index: int) -> Tuple[str, List[str], str]:
+ if not isinstance(rule, Rule):
+ raise _fail("rules must be Rule instances", index=index, rule=repr(rule))
+ rule_id = rule.rule_id
+ if not isinstance(rule_id, str) or not rule_id:
+ raise _fail("rule_id must be a non-empty string", rule=repr(rule_id))
+ if rule.rule_type != RuleType.IMPLICATION:
+ raise _fail(
+ "truth maintenance supports IMPLICATION rules only",
+ rule_id=rule_id,
+ rule_type=str(rule.rule_type),
+ )
+ confidence = rule.confidence
+ if isinstance(confidence, bool) or confidence != 1.0:
+ raise _fail(
+ "truth maintenance requires deterministic rules with confidence 1.0",
+ rule_id=rule_id,
+ confidence=repr(confidence),
+ )
+ if rule.handler is not None:
+ raise _fail("rules with handlers are not supported", rule_id=rule_id)
+ if rule.actions:
+ raise _fail("rules with actions are not supported", rule_id=rule_id)
+ conditions = rule.conditions
+ if not isinstance(conditions, (list, tuple)) or not conditions:
+ raise _fail(
+ "rule must have a non-empty list of conditions",
+ rule_id=rule_id,
+ )
+ condition_texts: List[str] = []
+ for condition in conditions:
+ if not isinstance(condition, str):
+ raise _fail(
+ "rule conditions must be atom strings",
+ rule_id=rule_id,
+ condition=repr(condition),
+ )
+ parse_atom(condition) # syntax check
+ condition_texts.append(normalize_atom(condition))
+ conclusion = rule.conclusion
+ if not isinstance(conclusion, str):
+ raise _fail(
+ "rule conclusion must be an atom string",
+ rule_id=rule_id,
+ conclusion=repr(conclusion),
+ )
+ return rule_id, condition_texts, conclusion
+
+
+def build_rule_snapshots(rules: Iterable[Rule]) -> Tuple[List[_RuleSnapshot], Dict[str, int]]:
+ """Validate rules and return ordered snapshots plus the arity registry.
+
+ The returned snapshots are sorted by (topological depth of the head
+ predicate, rule_id) so incremental re-evaluation can process them in a
+ single pass.
+ """
+ seen_rule_ids: Set[str] = set()
+ arities: Dict[str, int] = {}
+ entries: List[dict] = []
+ predicate_graph: Dict[str, Set[str]] = {}
+ predicate_depth: Dict[str, int] = {}
+
+ def register_arity(predicate: str, arity: int, where: str, rule_id: str) -> None:
+ existing = arities.get(predicate)
+ if existing is not None and existing != arity:
+ raise _fail(
+ "predicate arity conflict",
+ predicate=predicate,
+ existing_arity=existing,
+ conflicting_arity=arity,
+ location=where,
+ rule_id=rule_id,
+ )
+ arities[predicate] = arity
+
+ for index, rule in enumerate(rules):
+ rule_id, condition_texts, conclusion = _validate_rule_shape(rule, index)
+ if rule_id in seen_rule_ids:
+ raise _fail("duplicate rule_id", rule_id=rule_id)
+ seen_rule_ids.add(rule_id)
+
+ parsed_conditions = [parse_atom(text) for text in condition_texts]
+ parsed_conclusion = parse_atom(conclusion)
+ head_predicate, head_terms = parsed_conclusion
+
+ body_variables: Set[str] = set()
+ for predicate, terms in parsed_conditions:
+ register_arity(predicate, len(terms), "condition", rule_id)
+ body_variables.update(term for term in terms if _is_variable(term))
+ register_arity(head_predicate, len(head_terms), "conclusion", rule_id)
+ head_variables = {term for term in head_terms if _is_variable(term)}
+ unbound = head_variables - body_variables
+ if unbound:
+ raise _fail(
+ "conclusion variables must be bound by the rule body",
+ rule_id=rule_id,
+ unbound_variables=sorted(unbound),
+ )
+
+ body_predicates = {predicate for predicate, _ in parsed_conditions}
+ if head_predicate in body_predicates:
+ raise _fail(
+ "predicate dependency cycles are not supported "
+ "(a rule head must not appear in its own body)",
+ rule_id=rule_id,
+ predicate=head_predicate,
+ )
+ predicate_graph.setdefault(head_predicate, set()).update(body_predicates)
+ for predicate in body_predicates | {head_predicate}:
+ predicate_depth.setdefault(predicate, 0)
+
+ entries.append(
+ {
+ "rule_id": rule_id,
+ "conditions": tuple(condition_texts),
+ "conclusion": normalize_atom(conclusion),
+ "parsed_conditions": tuple(parsed_conditions),
+ "parsed_conclusion": parsed_conclusion,
+ "head_variables": frozenset(head_variables),
+ "body_variables": frozenset(body_variables),
+ "body_predicates": body_predicates,
+ }
+ )
+
+ _assign_depths(predicate_graph, predicate_depth)
+
+ snapshots: List[_RuleSnapshot] = []
+ for entry in entries:
+ head_predicate = entry["parsed_conclusion"][0]
+ snapshots.append(
+ _RuleSnapshot(
+ rule_id=entry["rule_id"],
+ conditions=entry["conditions"],
+ conclusion=entry["conclusion"],
+ parsed_conditions=entry["parsed_conditions"],
+ parsed_conclusion=entry["parsed_conclusion"],
+ head_variables=entry["head_variables"],
+ body_variables=entry["body_variables"],
+ order=(predicate_depth[head_predicate], entry["rule_id"]),
+ )
+ )
+ snapshots.sort(key=lambda snapshot: snapshot.order)
+ return snapshots, arities
+
+
+def _assign_depths(
+ predicate_graph: Dict[str, Set[str]], predicate_depth: Dict[str, int]
+) -> None:
+ """Compute topological depth per predicate, rejecting cycles."""
+ resolved: Dict[str, Optional[int]] = {}
+ for predicate in predicate_depth:
+ resolved[predicate] = None
+ for predicate in predicate_depth:
+ _visit(predicate, predicate_graph, resolved, [])
+ for predicate, depth in resolved.items():
+ predicate_depth[predicate] = depth # type: ignore[assignment]
+
+
+def _visit(
+ predicate: str,
+ predicate_graph: Dict[str, Set[str]],
+ resolved: Dict[str, Optional[int]],
+ stack: List[str],
+) -> int:
+ if predicate in stack:
+ cycle = stack[stack.index(predicate):] + [predicate]
+ raise _fail(
+ "predicate dependency cycles are not supported",
+ cycle=" -> ".join(cycle),
+ )
+ already = resolved.get(predicate)
+ if already is not None:
+ return already
+ stack.append(predicate)
+ depth = 0
+ for dependency in sorted(predicate_graph.get(predicate, ())):
+ depth = max(depth, _visit(dependency, predicate_graph, resolved, stack) + 1)
+ stack.pop()
+ resolved[predicate] = depth
+ return depth
\ No newline at end of file
diff --git a/semantica/reasoning/reasoner.py b/semantica/reasoning/reasoner.py
index cc16db40..2e929670 100644
--- a/semantica/reasoning/reasoner.py
+++ b/semantica/reasoning/reasoner.py
@@ -15,6 +15,9 @@ from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
+from ._rule_matching import match_pattern as _pure_match_pattern
+from ._rule_matching import match_rule as _pure_match_rule
+from ._rule_matching import substitute_variables as _pure_substitute_variables
class RuleType(Enum):
@@ -28,21 +31,15 @@ class RuleType(Enum):
def _substitute_variables(template: str, bindings: Dict[str, str]) -> str:
"""Substitute ``?var`` placeholders with their bound values, token-aware.
- A naive ``str.replace(f"?{var}", value)`` corrupts placeholders that share
- a prefix -- e.g. binding ``?x`` would also rewrite the ``?x`` inside ``?xy``.
- We replace every ``?word`` token in a single regex pass so that only whole
- variable names are matched (``\\w+`` never partially matches a longer name),
- leaving unbound placeholders untouched.
+ Delegates to :func:`semantica.reasoning._rule_matching.substitute_variables`;
+ kept as a module-level wrapper because actions and other private symbol
+ consumers depend on this name. A naive ``str.replace(f"?{var}", value)``
+ corrupts placeholders that share a prefix -- e.g. binding ``?x`` would
+ also rewrite the ``?x`` inside ``?xy``. The shared helper replaces every
+ ``?word`` token in a single regex pass so that only whole variable names
+ are matched, leaving unbound placeholders untouched.
"""
- if not bindings:
- return template
-
- def _replace(match: "re.Match") -> str:
- var_name = match.group(1)
- # Preserve unbound placeholders verbatim.
- return str(bindings[var_name]) if var_name in bindings else match.group(0)
-
- return re.sub(r"\?(\w+)", _replace, template)
+ return _pure_substitute_variables(template, bindings)
def _canonicalize_activation_value(
@@ -778,6 +775,10 @@ class Reasoner:
paired with the facts that satisfied each condition and the variable
bindings that produced them.
+ Delegates to :func:`semantica.reasoning._rule_matching.match_rule`,
+ passing ``self._match_pattern`` and ``self._substitute`` so subclass
+ overrides of those hooks keep working.
+
Returns:
List of (conclusion, matched_facts, bindings) tuples, where
matched_facts is the ordered list of facts bound to this rule's
@@ -786,77 +787,24 @@ class Reasoner:
"""
if not rule.conditions:
return []
-
- # self.facts is not mutated anywhere within this method, so sort it
- # once here rather than re-sorting on every (bindings, condition)
- # pair below -- sorted() was previously called once per inner-loop
- # entry, which re-allocates and re-sorts the full fact set repeatedly
- # and is a hot spot for larger fact sets.
- sorted_facts = sorted(self.facts)
-
- # Each entry pairs a set of variable bindings with the facts that were
- # matched to produce those bindings, so the facts survive alongside
- # the bindings as conditions accumulate.
- bindings_list: List[Tuple[Dict[str, str], List[str]]] = [({}, [])]
-
- for condition in rule.conditions:
- new_bindings_list = []
- for bindings, matched_facts in bindings_list:
- for fact in sorted_facts:
- match_bindings = self._match_pattern(condition, fact, bindings)
- if match_bindings is not None:
- new_bindings_list.append((match_bindings, matched_facts + [fact]))
- bindings_list = new_bindings_list
- if not bindings_list:
- break
-
- results = []
- for bindings, matched_facts in bindings_list:
- instantiated_conclusion = self._substitute(rule.conclusion, bindings)
- results.append((instantiated_conclusion, matched_facts, bindings))
-
- return results
-
+
+ return _pure_match_rule(
+ rule.conditions,
+ rule.conclusion,
+ self.facts,
+ pattern_matcher=self._match_pattern,
+ substituter=self._substitute,
+ )
+
def _match_pattern(self, pattern: str, fact: str, initial_bindings: Dict[str, str]) -> Optional[Dict[str, str]]:
- """Match a pattern against a fact with initial bindings."""
- # Split on ?var placeholders first, then escape only the literal segments.
- # This avoids re.escape() mangling the surrounding parentheses and ?
- # before the variable substitution step.
- segments = re.split(r"(\?\w+)", pattern)
- seen_vars: set = set()
- p_regex = ""
- for seg in segments:
- if seg.startswith("?"):
- var_name = seg[1:]
- if var_name in initial_bindings:
- # Already bound — require the exact literal value
- p_regex += re.escape(initial_bindings[var_name])
- elif var_name in seen_vars:
- # Same variable used twice — use a backreference
- p_regex += f"(?P={var_name})"
- else:
- p_regex += f"(?P<{var_name}>.+?)"
- seen_vars.add(var_name)
- else:
- p_regex += re.escape(seg)
- p_regex = f"^{p_regex}$"
+ """Match a pattern against a fact with initial bindings.
+
+ Delegates to :func:`semantica.reasoning._rule_matching.match_pattern`;
+ kept as an instance method so subclasses and tests can override this
+ hook and have :meth:`_match_rule` pick the override up.
+ """
+ return _pure_match_pattern(pattern, fact, initial_bindings, logger=self.logger)
- # Simple regex-based matcher for patterns like "Person(?x)" and facts like "Person(John)"
-
- try:
- match = re.match(p_regex, fact)
- if match:
- new_bindings = initial_bindings.copy()
- for var, value in match.groupdict().items():
- if var in new_bindings and new_bindings[var] != value:
- return None # Binding conflict
- new_bindings[var] = value
- return new_bindings
- except Exception as e:
- self.logger.warning(f"Error matching pattern '{pattern}' (regex: '{p_regex}') against fact '{fact}': {e}")
-
- return None
-
def _substitute(self, pattern: str, bindings: Dict[str, str]) -> str:
"""Substitute variables in a pattern with bound values."""
return _substitute_variables(pattern, bindings)
diff --git a/semantica/reasoning/truth_maintenance.py b/semantica/reasoning/truth_maintenance.py
new file mode 100644
index 00000000..f8533867
--- /dev/null
+++ b/semantica/reasoning/truth_maintenance.py
@@ -0,0 +1,542 @@
+"""Source-support based truth maintenance session.
+
+Implements the maintenance contract::
+
+ session.facts == closure(fixed_rules, facts_with_remaining_external_support)
+
+Public API is :class:`TruthMaintenanceSession`, created with a fixed rule set
+and updated through :meth:`TruthMaintenanceSession.apply` batches of
+assertions/retractions of :class:`FactSupport` entries.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from typing import Dict, FrozenSet, List, Set, Tuple
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ._truth_maintenance_validation import (
+ _RuleSnapshot,
+ build_rule_snapshots,
+ canonical_atom,
+ parse_atom,
+ validate_fact_text,
+)
+from .reasoner import Rule
+from .truth_maintenance_types import (
+ Derivation,
+ FactExplanation,
+ FactSupport,
+ MaintenanceDelta,
+)
+
+__all__ = ["TruthMaintenanceSession"]
+
+
+DerivationKey = Tuple[str, Tuple[str, ...], Tuple[Tuple[str, str], ...]]
+
+
+def _variable(term: str) -> bool:
+ return term.startswith("?")
+
+
+class _SessionState:
+ """Mutable working state; cloned per apply() batch for atomic commits."""
+
+ __slots__ = (
+ "active_facts",
+ "active_supports",
+ "arities",
+ "derivations",
+ "derivations_by_conclusion",
+ "derivations_by_rule",
+ "facts_by_pred",
+ "support_catalog",
+ "supports_by_fact",
+ )
+
+ def __init__(self) -> None:
+ self.support_catalog: Dict[str, str] = {}
+ self.active_supports: Dict[str, FactSupport] = {}
+ self.supports_by_fact: Dict[str, Set[str]] = {}
+ self.active_facts: Set[str] = set()
+ self.facts_by_pred: Dict[str, Set[str]] = {}
+ self.derivations: Dict[DerivationKey, Derivation] = {}
+ self.derivations_by_rule: Dict[str, Set[DerivationKey]] = {}
+ self.derivations_by_conclusion: Dict[str, Set[DerivationKey]] = {}
+ self.arities: Dict[str, int] = {}
+
+ def clone(self) -> _SessionState:
+ clone = _SessionState()
+ clone.support_catalog = dict(self.support_catalog)
+ clone.active_supports = dict(self.active_supports)
+ clone.supports_by_fact = {
+ fact: set(ids) for fact, ids in self.supports_by_fact.items()
+ }
+ clone.active_facts = set(self.active_facts)
+ clone.facts_by_pred = {
+ pred: set(facts) for pred, facts in self.facts_by_pred.items()
+ }
+ clone.derivations = dict(self.derivations)
+ clone.derivations_by_rule = {
+ rid: set(keys) for rid, keys in self.derivations_by_rule.items()
+ }
+ clone.derivations_by_conclusion = {
+ fact: set(keys) for fact, keys in self.derivations_by_conclusion.items()
+ }
+ clone.arities = dict(self.arities)
+ return clone
+
+ # -- fact helpers -------------------------------------------------
+
+ def add_fact(self, fact: str, affected: Set[str]) -> None:
+ self.active_facts.add(fact)
+ predicate, _terms = parse_atom(fact)
+ self.facts_by_pred.setdefault(predicate, set()).add(fact)
+ affected.add(predicate)
+
+ def remove_fact(self, fact: str, affected: Set[str]) -> None:
+ self.active_facts.discard(fact)
+ predicate, _terms = parse_atom(fact)
+ bucket = self.facts_by_pred.get(predicate)
+ if bucket is not None:
+ bucket.discard(fact)
+ if not bucket:
+ del self.facts_by_pred[predicate]
+ affected.add(predicate)
+
+ def has_active_fact(self, fact: str) -> bool:
+ return fact in self.active_facts
+
+ def has_support(self, fact: str) -> bool:
+ return bool(self.supports_by_fact.get(fact))
+
+ def has_derivation(self, fact: str) -> bool:
+ return bool(self.derivations_by_conclusion.get(fact))
+
+ # -- derivation helpers --------------------------------------------
+
+ def add_derivation(self, derivation: Derivation) -> None:
+ key: DerivationKey = (
+ derivation.rule_id,
+ derivation.premises,
+ derivation.bindings,
+ )
+ self.derivations[key] = derivation
+ self.derivations_by_rule.setdefault(derivation.rule_id, set()).add(key)
+ self.derivations_by_conclusion.setdefault(
+ derivation.conclusion, set()
+ ).add(key)
+
+ def remove_rule_derivations(self, rule_id: str) -> Set[str]:
+ """Drop every derivation of ``rule_id``; return affected conclusions."""
+ conclusions: Set[str] = set()
+ for key in list(self.derivations_by_rule.get(rule_id, ())):
+ derivation = self.derivations.pop(key)
+ self.derivations_by_rule[rule_id].discard(key)
+ bucket = self.derivations_by_conclusion.get(derivation.conclusion)
+ if bucket is not None:
+ bucket.discard(key)
+ if not bucket:
+ del self.derivations_by_conclusion[derivation.conclusion]
+ conclusions.add(derivation.conclusion)
+ if not self.derivations_by_rule.get(rule_id):
+ self.derivations_by_rule.pop(rule_id, None)
+ return conclusions
+
+
+class TruthMaintenanceSession:
+ """Maintains facts as the closure of fixed rules over externally supported facts.
+
+ Rules are snapshotted at construction time; later mutation of the original
+ :class:`~semantica.reasoning.reasoner.Rule` objects does not affect the
+ session. Updates are applied atomically: a failed batch leaves the
+ session (including support-id assignments) untouched.
+ """
+
+ def __init__(self, *, rules: Iterable[Rule]) -> None:
+ snapshots, arities = build_rule_snapshots(rules)
+ self._rules: List[_RuleSnapshot] = snapshots
+ self._state = _SessionState()
+ self._state.arities = dict(arities)
+ self._version = 0
+
+ # -- read-only views -------------------------------------------------
+
+ @property
+ def facts(self) -> FrozenSet[str]:
+ """Frozenset of all currently believed facts (explicit + derived)."""
+ return frozenset(self._state.active_facts)
+
+ @property
+ def version(self) -> int:
+ """Monotonic commit counter; unchanged for net-zero updates."""
+ return self._version
+
+ def explain(self, fact: str) -> FactExplanation:
+ """Explain one fact: explicit supports plus retained derivations."""
+ canonical = validate_fact_text(fact)
+ state = self._state
+ if canonical not in state.active_facts:
+ return FactExplanation(canonical, False, (), ())
+ support_ids = tuple(sorted(state.supports_by_fact.get(canonical, ())))
+ derivations = sorted(
+ (
+ state.derivations[key]
+ for key in state.derivations_by_conclusion.get(canonical, ())
+ ),
+ key=lambda item: (item.rule_id, item.premises, item.bindings),
+ )
+ return FactExplanation(canonical, True, support_ids, tuple(derivations))
+
+ # -- batched updates --------------------------------------------------
+
+ def apply(
+ self,
+ *,
+ assertions: Iterable[FactSupport] = (),
+ retractions: Iterable[str] = (),
+ ) -> MaintenanceDelta:
+ """Atomically apply one batch of assertions and retractions.
+
+ Raises :class:`~semantica.utils.exceptions.ValidationError` for any
+ malformed input without changing session state; wraps unexpected
+ internal errors in :class:`~semantica.utils.exceptions.ProcessingError`.
+ """
+ try:
+ assertion_items = _coerce_support_iterable(assertions)
+ retraction_items = _coerce_id_iterable(retractions)
+ effective_assertions, new_arities = self._validate_assertions(
+ assertion_items, retraction_items
+ )
+ except ValidationError:
+ raise
+ except Exception as exc: # unexpected input shaping failure
+ raise ProcessingError(
+ "truth maintenance batch validation failed",
+ validation_context={},
+ ) from exc
+
+ # Deduplicate while preserving order: a support id listed twice in one
+ # batch is one net retraction, not an error.
+ effective_retractions = [
+ rid
+ for rid in dict.fromkeys(retraction_items)
+ if rid in self._state.active_supports
+ ]
+ if not effective_assertions and not effective_retractions:
+ return MaintenanceDelta(
+ self._version, frozenset(), frozenset(), (), ()
+ )
+
+ try:
+ candidate = self._state.clone()
+ affected: Set[str] = set()
+ self._remove_retracted(candidate, effective_retractions, affected)
+ self._assert_supports(candidate, effective_assertions, affected)
+ candidate.arities.update(new_arities)
+ self._rematch_dirty_rules(candidate, affected)
+ except Exception as exc:
+ raise ProcessingError(
+ "truth maintenance update failed",
+ validation_context={"version": self._version},
+ ) from exc
+
+ return self._commit(candidate)
+
+ # -- validation -------------------------------------------------------
+
+ def _validate_assertions(
+ self, assertion_items: List[FactSupport], retraction_items: List[str]
+ ) -> Tuple[List[Tuple[str, str]], Dict[str, int]]:
+ state = self._state
+ batch_arities = dict(state.arities)
+ seen: Dict[str, str] = {}
+ effective: List[Tuple[str, str]] = []
+ for support in assertion_items:
+ if not isinstance(support, FactSupport):
+ raise ValidationError(
+ "assertions must contain FactSupport instances",
+ validation_context={"item_type": type(support).__name__},
+ )
+ support_id = support.support_id
+ if not isinstance(support_id, str) or not support_id:
+ raise ValidationError(
+ "support_id must be a non-empty string",
+ validation_context={"support_id": repr(support_id)},
+ )
+ canonical = validate_fact_text(support.fact)
+ predicate, terms = parse_atom(canonical)
+ _check_arity(batch_arities, predicate, len(terms))
+ previous = seen.get(support_id)
+ if previous is not None:
+ if previous != canonical:
+ raise ValidationError(
+ "support_id asserted twice with different facts in one batch",
+ validation_context={
+ "support_id": support_id,
+ "first_fact": previous,
+ "second_fact": canonical,
+ },
+ )
+ continue
+ seen[support_id] = canonical
+ registered = state.support_catalog.get(support_id)
+ if registered is not None and registered != canonical:
+ raise ValidationError(
+ "support_id is permanently bound to a different fact",
+ validation_context={
+ "support_id": support_id,
+ "registered_fact": registered,
+ "requested_fact": canonical,
+ },
+ )
+ if support_id not in state.active_supports:
+ effective.append((support_id, canonical))
+ overlap = set(seen) & set(retraction_items)
+ if overlap:
+ raise ValidationError(
+ "support_id appears in both assertions and retractions",
+ validation_context={
+ "conflicting_ids": tuple(sorted(overlap)),
+ },
+ )
+ # Predicates first observed in this batch: their arities must be
+ # persisted with the commit, otherwise a later batch could re-assert
+ # the same predicate with a different arity.
+ new_arities = {
+ predicate: arity
+ for predicate, arity in batch_arities.items()
+ if predicate not in state.arities
+ }
+ return effective, new_arities
+
+ # -- staged mutation on the candidate state ----------------------------
+
+ def _remove_retracted(
+ self,
+ candidate: _SessionState,
+ retraction_ids: List[str],
+ affected: Set[str],
+ ) -> None:
+ for support_id in retraction_ids:
+ support = candidate.active_supports.pop(support_id)
+ bucket = candidate.supports_by_fact.get(support.fact)
+ if bucket is not None:
+ bucket.discard(support_id)
+ if not bucket:
+ del candidate.supports_by_fact[support.fact]
+ if not candidate.has_support(support.fact) and not candidate.has_derivation(
+ support.fact
+ ):
+ if candidate.has_active_fact(support.fact):
+ candidate.remove_fact(support.fact, affected)
+
+ def _assert_supports(
+ self,
+ candidate: _SessionState,
+ assertions: List[Tuple[str, str]],
+ affected: Set[str],
+ ) -> None:
+ for support_id, canonical in assertions:
+ candidate.support_catalog[support_id] = canonical
+ candidate.active_supports[support_id] = FactSupport(support_id, canonical)
+ candidate.supports_by_fact.setdefault(canonical, set()).add(support_id)
+ if not candidate.has_active_fact(canonical):
+ candidate.add_fact(canonical, affected)
+
+ def _rematch_dirty_rules(
+ self, candidate: _SessionState, affected: Set[str]
+ ) -> None:
+ # Single pass in topological rule order: rules are visited after all
+ # rules that can produce their premises, so affected-set growth is
+ # observed in time.
+ for snapshot in self._rules:
+ body_predicates = {predicate for predicate, _ in snapshot.parsed_conditions}
+ if not body_predicates & affected:
+ continue
+ conclusions = candidate.remove_rule_derivations(snapshot.rule_id)
+ for premises, bindings, conclusion in self._match_rule(
+ snapshot, candidate
+ ):
+ candidate.add_derivation(
+ Derivation(snapshot.rule_id, conclusion, premises, bindings)
+ )
+ if not candidate.has_active_fact(conclusion):
+ candidate.add_fact(conclusion, affected)
+ for conclusion in sorted(conclusions):
+ if not candidate.has_active_fact(conclusion):
+ continue
+ if candidate.has_support(conclusion) or candidate.has_derivation(
+ conclusion
+ ):
+ continue
+ candidate.remove_fact(conclusion, affected)
+
+ def _match_rule(
+ self, snapshot: _RuleSnapshot, facts: _SessionState
+ ) -> List[Tuple[Tuple[str, ...], Tuple[Tuple[str, str], ...], str]]:
+ """Matcher seam: single delegation point for rule snapshot matching.
+
+ Delegates to the module-level ``_match_snapshot`` helper, which
+ enumerates matches against the candidate state's predicate-indexed
+ facts and filters facts whose term count differs from the pattern's
+ (term-level arity check). It intentionally does not call
+ ``_rule_matching.match_rule``: that helper matches against a flat
+ fact iterable, and its regex-based matcher would accept cross-arity
+ matches such as ``Q(?x)`` against ``Q(a, b)``. The two matchers are
+ kept semantically aligned by the parity and differential tests.
+
+ Exists to isolate matching responsibility and to give tests a
+ fault-injection and call-counting site; not part of the public API.
+ """
+ return _match_snapshot(snapshot, facts)
+
+ # -- commit -------------------------------------------------------------
+
+ def _commit(self, candidate: _SessionState) -> MaintenanceDelta:
+ state = self._state
+ old_facts = frozenset(state.active_facts)
+ new_facts = frozenset(candidate.active_facts)
+ added_facts = frozenset(new_facts - old_facts)
+ removed_facts = frozenset(old_facts - new_facts)
+ added_supports = tuple(
+ sorted(
+ (
+ support
+ for support_id, support in candidate.active_supports.items()
+ if support_id not in state.active_supports
+ ),
+ key=lambda item: item.support_id,
+ )
+ )
+ removed_supports = tuple(
+ sorted(
+ (
+ support
+ for support_id, support in state.active_supports.items()
+ if support_id not in candidate.active_supports
+ ),
+ key=lambda item: item.support_id,
+ )
+ )
+ if not (
+ added_facts
+ or removed_facts
+ or added_supports
+ or removed_supports
+ ):
+ return MaintenanceDelta(
+ self._version, frozenset(), frozenset(), (), ()
+ )
+ self._state = candidate
+ self._version += 1
+ return MaintenanceDelta(
+ self._version,
+ added_facts,
+ removed_facts,
+ added_supports,
+ removed_supports,
+ )
+
+
+def _check_arity(arities: Dict[str, int], predicate: str, arity: int) -> None:
+ registered = arities.get(predicate)
+ if registered is None:
+ arities[predicate] = arity
+ elif registered != arity:
+ raise ValidationError(
+ "predicate arity conflict",
+ validation_context={
+ "predicate": predicate,
+ "registered_arity": registered,
+ "observed_arity": arity,
+ },
+ )
+
+
+def _match_snapshot(
+ snapshot: _RuleSnapshot, state: _SessionState
+) -> List[Tuple[Tuple[str, ...], Tuple[Tuple[str, str], ...], str]]:
+ """Enumerate all matches of a rule snapshot against active facts.
+
+ Returns ``(premises, bindings, conclusion)`` tuples with premises in
+ condition order and bindings sorted by variable name.
+ """
+ conditions = snapshot.parsed_conditions
+ conclusion_predicate, conclusion_terms = snapshot.parsed_conclusion
+ results: List[Tuple[Tuple[str, ...], Tuple[Tuple[str, str], ...], str]] = []
+
+ def recurse(index: int, bindings: Dict[str, str], premises: List[str]) -> None:
+ if index == len(conditions):
+ substituted = tuple(
+ bindings.get(term, term) for term in conclusion_terms
+ )
+ results.append(
+ (
+ tuple(premises),
+ tuple(sorted(bindings.items())),
+ canonical_atom(conclusion_predicate, list(substituted)),
+ )
+ )
+ return
+ predicate, pattern_terms = conditions[index]
+ for fact in sorted(state.facts_by_pred.get(predicate, ())):
+ _pred, fact_terms = parse_atom(fact)
+ if len(fact_terms) != len(pattern_terms):
+ continue
+ local = dict(bindings)
+ consistent = True
+ for pattern_term, fact_term in zip(pattern_terms, fact_terms):
+ if _variable(pattern_term):
+ bound = local.get(pattern_term)
+ if bound is None:
+ local[pattern_term] = fact_term
+ elif bound != fact_term:
+ consistent = False
+ break
+ elif pattern_term != fact_term:
+ consistent = False
+ break
+ if consistent:
+ recurse(index + 1, local, premises + [fact])
+
+ recurse(0, {}, [])
+ return results
+
+
+def _coerce_support_iterable(value: object) -> List[FactSupport]:
+ if isinstance(value, (str, bytes)):
+ raise ValidationError(
+ "assertions must be an iterable of FactSupport, not a string",
+ validation_context={"received": repr(value)[:64]},
+ )
+ try:
+ return list(value) # type: ignore[arg-type]
+ except TypeError as exc:
+ raise ValidationError(
+ "assertions must be an iterable of FactSupport",
+ validation_context={"received_type": type(value).__name__},
+ ) from exc
+
+
+def _coerce_id_iterable(value: object) -> List[str]:
+ if isinstance(value, (str, bytes)):
+ raise ValidationError(
+ "retractions must be an iterable of support-id strings, not a string",
+ validation_context={"received": repr(value)[:64]},
+ )
+ try:
+ items = list(value) # type: ignore[arg-type]
+ except TypeError as exc:
+ raise ValidationError(
+ "retractions must be an iterable of support-id strings",
+ validation_context={"received_type": type(value).__name__},
+ ) from exc
+ for item in items:
+ if not isinstance(item, str) or not item:
+ raise ValidationError(
+ "retraction entries must be non-empty support-id strings",
+ validation_context={"entry": repr(item)[:64]},
+ )
+ return items
\ No newline at end of file
diff --git a/semantica/reasoning/truth_maintenance_types.py b/semantica/reasoning/truth_maintenance_types.py
new file mode 100644
index 00000000..2a2d66e0
--- /dev/null
+++ b/semantica/reasoning/truth_maintenance_types.py
@@ -0,0 +1,75 @@
+"""Public value types for truth maintenance.
+
+These dataclasses are the public API surface of
+:class:`semantica.reasoning.TruthMaintenanceSession`. All collections are
+immutable (tuples and frozensets) so snapshots returned by the session can
+never be mutated by later updates.
+"""
+
+from dataclasses import dataclass
+from typing import FrozenSet, Tuple
+
+__all__ = [
+ "Derivation",
+ "FactExplanation",
+ "FactSupport",
+ "MaintenanceDelta",
+]
+
+
+@dataclass(frozen=True)
+class FactSupport:
+ """An explicitly asserted fact identified by a lifetime-stable ID."""
+
+ support_id: str
+ fact: str
+
+
+@dataclass(frozen=True)
+class Derivation:
+ """A single rule application that concludes one fact from premises."""
+
+ rule_id: str
+ conclusion: str
+ premises: Tuple[str, ...]
+ bindings: Tuple[Tuple[str, str], ...]
+
+
+@dataclass(frozen=True)
+class FactExplanation:
+ """Everything known about why a fact currently holds."""
+
+ fact: str
+ active: bool
+ explicit_support_ids: Tuple[str, ...]
+ derivations: Tuple[Derivation, ...]
+
+
+@dataclass(frozen=True)
+class MaintenanceDelta:
+ """Net effect of one ``apply`` batch, observed after commit."""
+
+ version: int
+ added_facts: FrozenSet[str]
+ removed_facts: FrozenSet[str]
+ added_supports: Tuple[FactSupport, ...]
+ removed_supports: Tuple[FactSupport, ...]
+
+
+@dataclass(frozen=True)
+class _RuleSnapshot:
+ """Internal immutable copy of the subset of Rule the session relies on.
+
+ Snapshots are taken at session construction so later mutation of the
+ original ``Rule`` objects never changes session behavior.
+ """
+
+ rule_id: str
+ conditions: Tuple[str, ...]
+ conclusion: str
+ # Parsed view of conditions: tuple of (predicate, terms).
+ parsed_conditions: Tuple[Tuple[str, Tuple[str, ...]], ...]
+ parsed_conclusion: Tuple[str, Tuple[str, ...]]
+ head_variables: FrozenSet[str]
+ body_variables: FrozenSet[str]
+ order: Tuple[int, str]
\ No newline at end of file
diff --git a/tests/reasoning/test_reasoner.py b/tests/reasoning/test_reasoner.py
index f63cf2e8..2a0140a6 100644
--- a/tests/reasoning/test_reasoner.py
+++ b/tests/reasoning/test_reasoner.py
@@ -1,5 +1,7 @@
import unittest
-from semantica.reasoning.reasoner import Reasoner, Rule, RuleType, Fact, InferenceResult
+
+from semantica.reasoning.reasoner import Reasoner, Rule
+
class TestReasoner(unittest.TestCase):
def setUp(self):
@@ -259,5 +261,150 @@ class TestReasoner(unittest.TestCase):
self.assertEqual(result["x"], "John")
+# ---------------------------------------------------------------------------
+# Pure rule-matching helper (Task 1 of the truth maintenance plan): legacy
+# parity tests plus the dedicated helper entry points in
+# semantica.reasoning._rule_matching.
+# ---------------------------------------------------------------------------
+
+class TestRuleMatchingHelpers(unittest.TestCase):
+ """Legacy parity for the extracted pure matching functions."""
+
+ def _matched(self, conditions, conclusion, facts):
+ reasoner = Reasoner()
+ for fact in facts:
+ reasoner.add_fact(fact)
+ rule = Rule(
+ rule_id="r", name="r", conditions=conditions, conclusion=conclusion
+ )
+ return reasoner._match_rule(rule)
+
+ def test_whitespace_constants_match(self):
+ """Constants containing spaces must still match a single variable."""
+ matched = self._matched(
+ ["founded_by(?person, ?org)"],
+ "is_founder(?person, ?org)",
+ ["founded_by(Steve Jobs, Apple)"],
+ )
+ self.assertEqual(len(matched), 1)
+ conclusion, matched_facts, bindings = matched[0]
+ self.assertEqual(conclusion, "is_founder(Steve Jobs, Apple)")
+ self.assertEqual(matched_facts, ["founded_by(Steve Jobs, Apple)"])
+ self.assertEqual(bindings, {"person": "Steve Jobs", "org": "Apple"})
+
+ def test_repeated_variable_requires_equal_values(self):
+ """Pair(?x, ?x) must not match Pair(a, b) but must match Pair(a, a)."""
+ matched = self._matched(
+ ["Pair(?x, ?x)"], "Same(?x)", ["Pair(a, b)", "Pair(a, a)"]
+ )
+ self.assertEqual(len(matched), 1)
+ self.assertEqual(matched[0][0], "Same(a)")
+
+ def test_prebound_variable_carries_across_conditions(self):
+ """A variable bound in an earlier condition must constrain later ones."""
+ matched = self._matched(
+ ["Person(?x)", "Parent(?x, ?y)"],
+ "Child(?y, ?x)",
+ ["Person(John)", "Parent(John, Jane)", "Parent(Mary, Eve)"],
+ )
+ self.assertEqual(len(matched), 1)
+ self.assertEqual(matched[0][0], "Child(Jane, John)")
+
+ def test_three_condition_chain(self):
+ """Three accumulating conditions must produce full binding tuples."""
+ matched = self._matched(
+ ["A(?x)", "B(?x)", "C(?x, ?y)"],
+ "D(?x, ?y)",
+ ["A(a)", "B(a)", "C(a, b)", "B(z)"],
+ )
+ self.assertEqual(len(matched), 1)
+ conclusion, matched_facts, bindings = matched[0]
+ self.assertEqual(conclusion, "D(a, b)")
+ self.assertEqual(matched_facts, ["A(a)", "B(a)", "C(a, b)"])
+ self.assertEqual(bindings, {"x": "a", "y": "b"})
+
+ def test_variable_prefix_is_token_aware(self):
+ """Binding ?x must never rewrite the ?xy placeholder (prefix safety)."""
+ matched = self._matched(
+ ["P(?x, ?xy)"], "Q(?x, ?xy)", ["P(a, b)"]
+ )
+ self.assertEqual(len(matched), 1)
+ self.assertEqual(matched[0][0], "Q(a, b)")
+ self.assertEqual(matched[0][2], {"x": "a", "xy": "b"})
+
+ def test_unbound_placeholders_stay_verbatim(self):
+ """Substituting a subset of variables must leave others untouched."""
+ reasoner = Reasoner()
+ result = reasoner._substitute("Q(?x, ?xy)", {"x": "a"})
+ self.assertEqual(result, "Q(a, ?xy)")
+
+ def test_rule_without_conditions_matches_nothing(self):
+ """A rule with an empty conditions list must produce no matches."""
+ reasoner = Reasoner()
+ rule = Rule(rule_id="r", name="r", conditions=[], conclusion="Ready()")
+ self.assertEqual(reasoner._match_rule(rule), [])
+
+
+from semantica.reasoning import _rule_matching
+
+
+class TestPureMatchingModule(unittest.TestCase):
+ """Direct entry points of the extracted pure helper module."""
+
+ def test_substitute_variables(self):
+ self.assertEqual(
+ _rule_matching.substitute_variables("Q(?x, ?y)", {"x": "a", "y": "b"}),
+ "Q(a, b)",
+ )
+
+ def test_substitute_variables_prefix_safe(self):
+ self.assertEqual(
+ _rule_matching.substitute_variables("Q(?x, ?xy)", {"x": "a"}),
+ "Q(a, ?xy)",
+ )
+
+ def test_match_pattern_returns_bindings(self):
+ bindings = _rule_matching.match_pattern(
+ "P(?x, ?y)", "P(a, b)", {}, logger=Reasoner().logger
+ )
+ self.assertEqual(bindings, {"x": "a", "y": "b"})
+
+ def test_match_pattern_binding_conflict(self):
+ bindings = _rule_matching.match_pattern(
+ "P(?x, ?y)", "P(a, a)", {"x": "b"}, logger=Reasoner().logger
+ )
+ self.assertIsNone(bindings)
+
+ def test_match_rule_pure(self):
+ matched = _rule_matching.match_rule(
+ ["A(?x)", "B(?x)"],
+ "C(?x)",
+ ["A(a)", "B(a)", "B(z)"],
+ pattern_matcher=_rule_matching.match_pattern,
+ substituter=_rule_matching.substitute_variables,
+ )
+ self.assertEqual(len(matched), 1)
+ conclusion, matched_facts, bindings = matched[0]
+ self.assertEqual(conclusion, "C(a)")
+ self.assertEqual(matched_facts, ["A(a)", "B(a)"])
+ self.assertEqual(bindings, {"x": "a"})
+
+ def test_match_rule_empty_conditions(self):
+ matched = _rule_matching.match_rule(
+ [], "C()", [], pattern_matcher=None, substituter=None
+ )
+ self.assertEqual(matched, [])
+
+
+def test_match_rule_keeps_pattern_override(monkeypatch):
+ from semantica.reasoning import Reasoner, Rule
+
+ reasoner = Reasoner()
+ reasoner.add_fact("A(a)")
+ rule = Rule("r", "r", ["A(?x)"], "B(?x)")
+ monkeypatch.setattr(reasoner, "_match_pattern", lambda *args: None)
+ assert reasoner._match_rule(rule) == []
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/reasoning/test_truth_maintenance.py b/tests/reasoning/test_truth_maintenance.py
new file mode 100644
index 00000000..6628e75d
--- /dev/null
+++ b/tests/reasoning/test_truth_maintenance.py
@@ -0,0 +1,439 @@
+"""Public behavior tests for TruthMaintenanceSession (PR1 Task 2).
+
+Covers the acceptance scenarios from the implementation plan: multi-support
+retraction, alternative derivations, net replacement, explicit vs derived
+support, cycle rejection, atomic failed batches, and the full input
+validation matrix.
+"""
+
+from typing import FrozenSet, get_type_hints
+
+import pytest
+
+from semantica.reasoning import FactSupport, Rule, TruthMaintenanceSession
+from semantica.utils.exceptions import ValidationError
+
+
+def rule(rid, conditions, conclusion):
+ return Rule(rid, rid, conditions, conclusion)
+
+
+def test_chain_retraction():
+ session = TruthMaintenanceSession(rules=[
+ rule("ab", ["A(?x)"], "B(?x)"),
+ rule("bc", ["B(?x)"], "C(?x)"),
+ ])
+ session.apply(assertions=[FactSupport("s1", "A(a)")])
+ assert session.facts == frozenset({"A(a)", "B(a)", "C(a)"})
+ delta = session.apply(retractions=["s1"])
+ assert delta.removed_facts == frozenset({"A(a)", "B(a)", "C(a)"})
+ assert not session.facts
+
+
+def test_alternative_derivation_is_retained():
+ session = TruthMaintenanceSession(rules=[
+ rule("ac", ["A(?x)"], "C(?x)"),
+ rule("bc", ["B(?x)"], "C(?x)"),
+ ])
+ session.apply(assertions=[FactSupport("a", "A(x)")])
+ session.apply(assertions=[FactSupport("b", "B(x)")])
+ assert len(session.explain("C(x)").derivations) == 2
+ session.apply(retractions=["a"])
+ assert session.facts == frozenset({"B(x)", "C(x)"})
+ assert len(session.explain("C(x)").derivations) == 1
+ session.apply(retractions=["b"])
+ assert not session.facts
+
+
+def test_multi_source_and_net_replacement():
+ session = TruthMaintenanceSession(rules=[rule("ab", ["A(?x)"], "B(?x)")])
+ session.apply(assertions=[FactSupport("v1", "A(x)")])
+ old = session.version
+ delta = session.apply(
+ assertions=[FactSupport("v2", "A(x)")], retractions=["v1"],
+ )
+ assert delta.version == old + 1
+ assert not delta.added_facts and not delta.removed_facts
+ assert delta.removed_supports == (FactSupport("v1", "A(x)"),)
+ assert delta.added_supports == (FactSupport("v2", "A(x)"),)
+ session.apply(assertions=[FactSupport("v3", "A(x)")])
+ session.apply(retractions=["v2"])
+ assert session.explain("A(x)").explicit_support_ids == ("v3",)
+ assert "B(x)" in session.facts
+
+
+def test_explicit_and_derived_support():
+ session = TruthMaintenanceSession(rules=[rule("ac", ["A(?x)"], "C(?x)")])
+ session.apply(assertions=[FactSupport("a", "A(x)"), FactSupport("c", "C(x)")])
+ session.apply(retractions=["a"])
+ assert session.facts == frozenset({"C(x)"})
+ session.apply(retractions=["c"])
+ assert not session.facts
+
+
+def test_unsupported_cycle_rejected():
+ with pytest.raises(ValidationError):
+ TruthMaintenanceSession(rules=[
+ rule("ab", ["A(?x)"], "B(?x)"),
+ rule("ba", ["B(?x)"], "A(?x)"),
+ ])
+
+
+def test_failed_batch_is_atomic():
+ session = TruthMaintenanceSession(rules=[rule("ab", ["A(?x)"], "B(?x)")])
+ session.apply(assertions=[FactSupport("s", "A(x)")])
+ before = (session.version, session.facts, session.explain("B(x)"))
+ with pytest.raises(ValidationError):
+ session.apply(assertions=[
+ FactSupport("new", "A(y)"), FactSupport("s", "A(z)"),
+ ])
+ assert (session.version, session.facts, session.explain("B(x)")) == before
+ # A failed batch must not reserve the new support ID in the catalog.
+ session.apply(assertions=[FactSupport("new", "A(z)")])
+ assert "B(z)" in session.facts
+
+
+# ---------------------------------------------------------------------------
+# Validation matrix
+# ---------------------------------------------------------------------------
+
+
+def test_whitespace_normalization():
+ session = TruthMaintenanceSession(
+ rules=[rule("ab", ["A(?x, ?y)"], "B(?x, ?y)")]
+ )
+ session.apply(assertions=[FactSupport("s", "A( a , b )")])
+ assert session.facts == frozenset({"A(a, b)", "B(a, b)"})
+
+
+def test_zero_arity_facts():
+ session = TruthMaintenanceSession(rules=[
+ rule("rg", ["Ready()"], "Go()"),
+ ])
+ session.apply(assertions=[FactSupport("r", "Ready()"), FactSupport("g", "Go()")])
+ assert session.facts == frozenset({"Ready()", "Go()"})
+
+
+def test_repeated_variable_requires_equal_values():
+ session = TruthMaintenanceSession(rules=[
+ rule("p", ["Pair(?x, ?x)"], "Same(?x)"),
+ ])
+ session.apply(assertions=[FactSupport("s", "Pair(a, b)")])
+ assert session.facts == frozenset({"Pair(a, b)"})
+ session.apply(assertions=[FactSupport("t", "Pair(c, c)")])
+ assert session.facts == frozenset({"Pair(a, b)", "Pair(c, c)", "Same(c)"})
+
+
+def test_duplicate_premise_rule_single_derivation():
+ session = TruthMaintenanceSession(rules=[
+ rule("r", ["A(?x)", "A(?x)"], "B(?x)"),
+ ])
+ session.apply(assertions=[FactSupport("s", "A(a)")])
+ assert len(session.explain("B(a)").derivations) == 1
+ session.apply(retractions=["s"])
+ assert not session.facts
+
+
+def test_two_premise_matches_keep_both_derivations():
+ session = TruthMaintenanceSession(rules=[
+ rule("r", ["A(?x, ?y)"], "B(?x)"),
+ ])
+ session.apply(assertions=[
+ FactSupport("s1", "A(a, b)"),
+ FactSupport("s2", "A(a, c)"),
+ ])
+ assert len(session.explain("B(a)").derivations) == 2
+ session.apply(retractions=["s1"])
+ assert "B(a)" in session.facts
+ assert len(session.explain("B(a)").derivations) == 1
+
+
+def test_head_variable_must_be_bound():
+ with pytest.raises(ValidationError):
+ TruthMaintenanceSession(rules=[rule("r", ["A(?x)"], "B(?y)")])
+
+
+def test_fixed_arity():
+ with pytest.raises(ValidationError):
+ TruthMaintenanceSession(rules=[
+ rule("r1", ["A(?x)"], "B(?x)"),
+ rule("r2", ["A(?x, ?y)"], "C(?x)"),
+ ])
+ session = TruthMaintenanceSession(rules=[rule("ab", ["A(?x)"], "B(?x)")])
+ session.apply(assertions=[FactSupport("s", "A(a)")])
+ with pytest.raises(ValidationError):
+ session.apply(assertions=[FactSupport("t", "A(a, b)")])
+
+
+def test_asserted_predicate_arity_persists_across_batches():
+ # Predicates first introduced by an assertion must keep that arity for
+ # the session lifetime; a later batch cannot widen or narrow it.
+ session = TruthMaintenanceSession(rules=[])
+ session.apply(assertions=[FactSupport("s1", "Q(alice)")])
+ with pytest.raises(ValidationError):
+ session.apply(assertions=[FactSupport("s2", "Q(alice, bob)")])
+ # Same-arity re-assertion of the already-registered predicate is fine.
+ session.apply(assertions=[FactSupport("s3", "Q(bob)")])
+ assert session.facts == frozenset({"Q(alice)", "Q(bob)"})
+
+
+def test_rule_feature_restrictions():
+ with pytest.raises(ValidationError):
+ TruthMaintenanceSession(rules=[
+ Rule("r", "r", ["A(?x)"], "B(?x)", rule_type=__import__(
+ "semantica.reasoning", fromlist=["RuleType"]
+ ).RuleType.EQUIVALENCE),
+ ])
+ with pytest.raises(ValidationError):
+ TruthMaintenanceSession(rules=[
+ Rule("r", "r", ["A(?x)"], "B(?x)", confidence=0.5),
+ ])
+ with pytest.raises(ValidationError):
+ TruthMaintenanceSession(rules=[
+ Rule("r", "r", ["A(?x)"], "B(?x)", handler=lambda x: x),
+ ])
+ with pytest.raises(ValidationError):
+ TruthMaintenanceSession(rules=[
+ Rule("r", "r", ["A(?x)"], "B(?x)", actions=[object()]),
+ ])
+
+
+def test_rule_snapshot_is_isolated_from_mutation():
+ r = rule("ab", ["A(?x)"], "B(?x)")
+ session = TruthMaintenanceSession(rules=[r])
+ r.conditions.append("ZZZ(?x)")
+ r.conclusion = "Hacked(?x)"
+ session.apply(assertions=[FactSupport("s", "A(a)")])
+ assert session.facts == frozenset({"A(a)", "B(a)"})
+
+
+def test_returned_snapshots_are_immutable():
+ session = TruthMaintenanceSession(rules=[rule("ab", ["A(?x)"], "B(?x)")])
+ delta = session.apply(assertions=[FactSupport("s", "A(a)")])
+ facts = session.facts
+ explanation = session.explain("A(a)")
+ session.apply(retractions=["s"])
+ assert facts == frozenset({"A(a)", "B(a)"})
+ assert explanation.explicit_support_ids == ("s",)
+ assert delta.added_facts == frozenset({"A(a)", "B(a)"})
+
+
+def test_duplicate_noop_batches():
+ session = TruthMaintenanceSession(rules=[rule("ab", ["A(?x)"], "B(?x)")])
+ session.apply(assertions=[FactSupport("s", "A(a)")])
+ version = session.version
+ delta = session.apply(assertions=[FactSupport("s", "A(a)")])
+ assert delta.version == version
+ assert not delta.added_facts and not delta.removed_facts
+ assert not delta.added_supports and not delta.removed_supports
+ delta = session.apply(retractions=["unknown-id"])
+ assert delta.version == version
+ assert not delta.removed_facts
+ delta = session.apply()
+ assert delta.version == version
+
+
+def test_duplicate_retraction_ids_are_idempotent():
+ session = TruthMaintenanceSession(rules=[rule("ab", ["A(?x)"], "B(?x)")])
+ session.apply(assertions=[FactSupport("s", "A(a)")])
+ delta = session.apply(retractions=["s", "s"])
+ assert delta.removed_facts == frozenset({"A(a)", "B(a)"})
+ assert delta.removed_supports == (FactSupport("s", "A(a)"),)
+ assert not session.facts
+
+
+def test_duplicate_retraction_with_mixed_ids():
+ session = TruthMaintenanceSession(rules=[rule("ab", ["A(?x)"], "B(?x)")])
+ session.apply(assertions=[FactSupport("s1", "A(a)"), FactSupport("s2", "A(b)")])
+ session.apply(retractions=["s2", "s1", "s2", "unknown-id"])
+ assert session.facts == frozenset()
+
+
+def test_facts_annotation_resolvable_at_runtime():
+ hints = get_type_hints(TruthMaintenanceSession.facts.fget)
+ assert hints["return"] == FrozenSet[str]
+
+
+def test_retracted_id_can_reassert_same_fact_only():
+ session = TruthMaintenanceSession(rules=[rule("ab", ["A(?x)"], "B(?x)")])
+ session.apply(assertions=[FactSupport("s", "A(a)")])
+ session.apply(retractions=["s"])
+ session.apply(assertions=[FactSupport("s", "A(a)")])
+ assert session.facts == frozenset({"A(a)", "B(a)"})
+ session.apply(retractions=["s"])
+ with pytest.raises(ValidationError):
+ session.apply(assertions=[FactSupport("s", "A(b)")])
+
+
+def test_same_id_in_assertions_and_retractions():
+ session = TruthMaintenanceSession(rules=[rule("ab", ["A(?x)"], "B(?x)")])
+ session.apply(assertions=[FactSupport("s", "A(a)")])
+ before = (session.version, session.facts)
+ with pytest.raises(ValidationError):
+ session.apply(
+ assertions=[FactSupport("s", "A(a)")], retractions=["s"],
+ )
+ assert (session.version, session.facts) == before
+
+
+def test_generator_inputs():
+ session = TruthMaintenanceSession(rules=[rule("ab", ["A(?x)"], "B(?x)")])
+ gen = (FactSupport(f"s{i}", f"A(c{i})") for i in range(3))
+ session.apply(assertions=gen)
+ assert session.facts == frozenset(
+ {"A(c0)", "A(c1)", "A(c2)", "B(c0)", "B(c1)", "B(c2)"}
+ )
+ session.apply(retractions=iter(["s0", "s1"]))
+ assert "B(c0)" not in session.facts
+ assert "B(c2)" in session.facts
+
+
+def test_string_iterable_rejected():
+ session = TruthMaintenanceSession(rules=[rule("ab", ["A(?x)"], "B(?x)")])
+ with pytest.raises(ValidationError):
+ session.apply(assertions="abc")
+ with pytest.raises(ValidationError):
+ session.apply(retractions="abc")
+
+
+# ---------------------------------------------------------------------------
+# Syntax validation
+# ---------------------------------------------------------------------------
+
+
[email protected]("bad_fact", [
+ "A", # not an atom
+ 'P("Alice Smith")', # quoted constant
+ "P(f(a))", # nested term
+ "P(?x)", # variable as fact argument
+ "P(a,)", # trailing comma
+ "P(,a)", # leading comma
+ "P(a,,b)", # empty argument
+ "1P(a)", # identifier must start with letter/underscore
+ "P(a b)", # whitespace inside constant
+])
+def test_invalid_fact_syntax_rejected(bad_fact):
+ session = TruthMaintenanceSession(rules=[rule("ab", ["A(?x)"], "B(?x)")])
+ with pytest.raises(ValidationError):
+ session.apply(assertions=[FactSupport("s", bad_fact)])
+
+
[email protected]("bad_rule", [
+ (["A(?x)"], "B"), # head not an atom
+ (["A(?x)"], "B(?x)(?y)"), # malformed head
+ ([], "B(?x)"), # empty body
+])
+def test_invalid_rule_syntax_rejected(bad_rule):
+ conditions, conclusion = bad_rule
+ with pytest.raises(ValidationError):
+ TruthMaintenanceSession(rules=[rule("r", conditions, conclusion)])
+
+
+def test_duplicate_rule_id_rejected():
+ with pytest.raises(ValidationError):
+ TruthMaintenanceSession(rules=[
+ rule("r", ["A(?x)"], "B(?x)"),
+ rule("r", ["A(?x)"], "C(?x)"),
+ ])
+
+
+def test_explain_unknown_fact():
+ session = TruthMaintenanceSession(rules=[rule("ab", ["A(?x)"], "B(?x)")])
+ explanation = session.explain("Unknown(a)")
+ assert explanation.active is False
+ assert explanation.explicit_support_ids == ()
+ assert explanation.derivations == ()
+
+
+def test_initial_session_state():
+ session = TruthMaintenanceSession(rules=[rule("ab", ["A(?x)"], "B(?x)")])
+ assert session.version == 0
+ assert session.facts == frozenset()
+
+
+def test_bindings_sorted_and_premises_ordered():
+ session = TruthMaintenanceSession(rules=[
+ rule("r", ["A(?y)", "B(?x)"], "C(?x, ?y)"),
+ ])
+ session.apply(assertions=[
+ FactSupport("a1", "A(v)"), FactSupport("b1", "B(w)"),
+ ])
+ derivations = session.explain("C(w, v)").derivations
+ assert len(derivations) == 1
+ d = derivations[0]
+ assert d.rule_id == "r"
+
+
+# -- Task 3: processing failure atomicity and targeted maintenance ------------
+
+
+def test_processing_failure_rolls_back(monkeypatch):
+ from semantica.utils.exceptions import ProcessingError
+
+ session = TruthMaintenanceSession(rules=[rule("ab", ["A(?x)"], "B(?x)")])
+ session.apply(assertions=[FactSupport("old", "A(x)")])
+ before = (session.version, session.facts, session.explain("B(x)"))
+ real_matcher = session._match_rule
+
+ def fail(*args, **kwargs):
+ raise RuntimeError("injected evaluator failure")
+
+ monkeypatch.setattr(session, "_match_rule", fail)
+ with pytest.raises(ProcessingError) as error:
+ session.apply(
+ assertions=[FactSupport("new", "A(y)")], retractions=["old"]
+ )
+ assert isinstance(error.value.__cause__, RuntimeError)
+ assert (session.version, session.facts, session.explain("B(x)")) == before
+ monkeypatch.setattr(session, "_match_rule", real_matcher)
+ session.apply(assertions=[FactSupport("new", "A(y)")], retractions=["old"])
+ assert session.facts == frozenset({"A(y)", "B(y)"})
+
+
+def test_retraction_without_fact_change_skips_matching(monkeypatch):
+ session = TruthMaintenanceSession(rules=[rule("ab", ["A(?x)"], "B(?x)")])
+ session.apply(assertions=[
+ FactSupport("s1", "A(x)"), FactSupport("s2", "A(x)"),
+ ])
+ calls = []
+ real_matcher = session._match_rule
+
+ def counting(*args, **kwargs):
+ calls.append(args[0].rule_id)
+ return real_matcher(*args, **kwargs)
+
+ monkeypatch.setattr(session, "_match_rule", counting)
+ delta = session.apply(retractions=["s1"])
+ assert not calls
+ assert not delta.added_facts and not delta.removed_facts
+ assert delta.removed_supports == (FactSupport("s1", "A(x)"),)
+ assert session.facts == frozenset({"A(x)", "B(x)"})
+ explanation = session.explain("B(x)")
+ assert explanation.active is True
+ assert len(explanation.derivations) == 1
+
+
+def test_assertion_rematches_only_dependent_rule_closure(monkeypatch):
+ session = TruthMaintenanceSession(rules=[
+ rule("ab", ["A(?x)"], "B(?x)"),
+ rule("bc", ["B(?x)"], "C(?x)"),
+ rule("zw", ["Z(?x)"], "W(?x)"),
+ ])
+ session.apply(assertions=[FactSupport("z", "Z(q)")])
+ calls = []
+ real_matcher = session._match_rule
+
+ def counting(snapshot, facts):
+ calls.append(snapshot.rule_id)
+ return real_matcher(snapshot, facts)
+
+ monkeypatch.setattr(session, "_match_rule", counting)
+ session.apply(assertions=[FactSupport("a", "A(x)")])
+ assert calls == ["ab", "bc"]
+ assert "zw" not in calls
+ assert session.facts == frozenset({"A(x)", "B(x)", "C(x)", "Z(q)", "W(q)"})
+ explanation = session.explain("C(x)")
+ assert explanation.active is True
+ assert len(explanation.derivations) == 1
+ assert explanation.derivations[0].rule_id == "bc"
+ assert session.explain("W(q)").derivations[0].rule_id == "zw"
\ No newline at end of file
diff --git a/tests/reasoning/test_truth_maintenance_differential.py b/tests/reasoning/test_truth_maintenance_differential.py
new file mode 100644
index 00000000..3a352814
--- /dev/null
+++ b/tests/reasoning/test_truth_maintenance_differential.py
@@ -0,0 +1,387 @@
+"""Differential tests comparing incremental session updates with an independent oracle.
+
+The oracle here is intentionally naive: it re-computes the full closure from
+scratch by enumerating every substitution over the constant domain, using only
+structured tuple atoms built inside this file. It never touches the session
+parser, matcher, dependency index, or ``Reasoner.forward_chain()``.
+
+Randomized workload (seeds 0..19):
+- 12 acyclic rules over predicates P0..P5 (arity 2, head index > body indices)
+- 15 initial external supports, then 60 update batches (0..3 assertions and
+ 0..3 retractions per batch; support ids never cross within a batch)
+- support ids are permanently bound to their atom; retired ids may be
+ re-activated later with the same atom, and duplicate sources are allowed
+- random invalid inputs (re-binding a support id to a different fact) must be
+ rejected atomically without state changes
+
+Each batch compares facts, per-fact direct derivations, explicit supports,
+version, and the net delta. On failure the assertion message carries the seed,
+the rules, the completed events, and the failing batch.
+
+Metamorphic checks:
+- reordering rules and initial supports yields the same facts and derivations
+- asserting a support and then retracting it restores the logical state
+"""
+
+import itertools
+import random
+
+import pytest
+
+from semantica.reasoning import FactSupport, Rule, TruthMaintenanceSession
+from semantica.utils.exceptions import ValidationError
+
+CONSTANTS = ("a", "b", "c")
+VARIABLES = ("?x", "?y")
+PREDICATES = tuple(f"P{i}" for i in range(6))
+
+
+# --------------------------------------------------------------------------
+# Tuple-atom helpers (test-internal, independent of the session parser)
+# --------------------------------------------------------------------------
+
+def atom_text(atom):
+ predicate, terms = atom
+ return "{}({})".format(predicate, ", ".join(terms))
+
+
+def parse_session_fact(text):
+ predicate, _, rest = text.partition("(")
+ return (predicate, tuple(rest.rstrip(")").split(", ")))
+
+
+def rule_text(rule):
+ _rule_id, body_atoms, head_atom = rule
+ return "{} <- {}".format(atom_text(head_atom), ", ".join(atom_text(a) for a in body_atoms))
+
+
+# --------------------------------------------------------------------------
+# Independent oracle: exhaustive substitution enumeration
+# --------------------------------------------------------------------------
+
+def groundings(rule, facts):
+ """Enumerate every substitution of the rule variables over the constant domain.
+
+ Returns a list of ``(conclusion, premises, bindings)`` tuples where
+ ``premises`` preserves condition order and ``bindings`` is sorted by
+ variable name.
+ """
+ _rule_id, body_atoms, head_atom = rule
+ variables = sorted(
+ {term for atom in body_atoms + (head_atom,) for term in atom[1] if term.startswith("?")}
+ )
+ domain = set()
+ for fact in facts:
+ domain.update(fact[1])
+ for atom in body_atoms + (head_atom,):
+ domain.update(term for term in atom[1] if not term.startswith("?"))
+ domain = sorted(domain)
+ results = []
+ for combo in itertools.product(domain, repeat=len(variables)):
+ substitution = dict(zip(variables, combo))
+ premises = []
+ satisfied = True
+ for predicate, terms in body_atoms:
+ grounded = (predicate, tuple(substitution.get(term, term) for term in terms))
+ if grounded not in facts:
+ satisfied = False
+ break
+ premises.append(grounded)
+ if not satisfied:
+ continue
+ head_predicate, head_terms = head_atom
+ conclusion = (head_predicate, tuple(substitution.get(term, term) for term in head_terms))
+ bindings = tuple(sorted(substitution.items()))
+ results.append((conclusion, tuple(premises), bindings))
+ return results
+
+
+def oracle_closure(rules, support_facts):
+ """Iterate all rules to a fixed point starting from the explicit facts."""
+ current = set(support_facts)
+ while True:
+ derived = set(current)
+ for rule in rules:
+ for conclusion, _premises, _bindings in groundings(rule, current):
+ derived.add(conclusion)
+ if derived == current:
+ return current
+ current = derived
+
+
+def all_derivations(rules, facts):
+ """Enumerate every direct derivation on the final closure.
+
+ Includes alternative derivations for conclusions that are already present.
+ """
+ derivations = {}
+ for rule in rules:
+ for conclusion, premises, bindings in groundings(rule, facts):
+ derivations.setdefault(conclusion, []).append((rule[0], premises, bindings))
+ for entries in derivations.values():
+ entries.sort(key=lambda d: (d[0], tuple(atom_text(p) for p in d[1]), d[2]))
+ return derivations
+
+
+# --------------------------------------------------------------------------
+# Random workload generation
+# --------------------------------------------------------------------------
+
+def generate_rules(rng):
+ """12 acyclic rules: head predicate index strictly greater than body indices."""
+ rules = []
+ for index in range(12):
+ head_index = rng.randint(1, 5)
+ body_atoms = []
+ body_variables = set()
+ for _ in range(rng.randint(1, 3)):
+ predicate = f"P{rng.randint(0, head_index - 1)}"
+ terms = tuple(rng.choice(CONSTANTS + VARIABLES) for _ in range(2))
+ body_variables.update(term for term in terms if term.startswith("?"))
+ body_atoms.append((predicate, terms))
+ head_choices = list(body_variables) + list(CONSTANTS)
+ head_terms = tuple(rng.choice(head_choices) for _ in range(2))
+ rules.append((f"r{index}", tuple(body_atoms), (f"P{head_index}", head_terms)))
+ return tuple(rules)
+
+
+def random_ground_atom(rng):
+ predicate = rng.choice(PREDICATES)
+ terms = tuple(rng.choice(CONSTANTS) for _ in range(2))
+ return (predicate, terms)
+
+
+def generate_batch(rng, catalog, supports, counter):
+ """One update batch: (assertions, retractions, invalid_or_None).
+
+ Assertions and retractions never share ids inside a batch. Retired ids may
+ be re-activated, but only with their permanently bound atom.
+ """
+ retractions = rng.sample(sorted(supports), min(len(supports), rng.randint(0, 3)))
+ assertions = []
+ retired = sorted(sid for sid in catalog if sid not in supports)
+ for _ in range(rng.randint(0, 3)):
+ if retired and rng.random() < 0.5:
+ sid = retired.pop(rng.randrange(len(retired)))
+ fact = catalog[sid]
+ else:
+ sid = f"s{next(counter)}"
+ fact = random_ground_atom(rng)
+ catalog[sid] = fact
+ if any(sid == existing for existing, _fact in assertions):
+ continue
+ assertions.append((sid, fact))
+ invalid = None
+ eligible = sorted(sid for sid in supports if sid not in retractions)
+ if eligible and rng.random() < 0.2:
+ sid = rng.choice(eligible)
+ different = random_ground_atom(rng)
+ while different == catalog[sid]:
+ different = random_ground_atom(rng)
+ invalid = (sid, different)
+ return assertions, retractions, invalid
+
+
+def build_session(rules):
+ return TruthMaintenanceSession(
+ rules=[
+ Rule(rule_id, rule_id, [atom_text(a) for a in body], atom_text(head))
+ for rule_id, body, head in rules
+ ]
+ )
+
+
+def compare_session(session, rules, supports, seed, stage, events):
+ """Compare the full logical state of the session against the oracle."""
+ closure = oracle_closure(rules, set(supports.values()))
+ session_facts = {parse_session_fact(text) for text in session.facts}
+ assert session_facts == closure, (
+ f"facts mismatch\nseed={seed}\nstage={stage}\nrules={[rule_text(r) for r in rules]}\nevents={events}\n"
+ f"session={sorted(session_facts)}\noracle={sorted(closure)}"
+ )
+ derivations = all_derivations(rules, closure)
+ for fact in closure:
+ explanation = session.explain(atom_text(fact))
+ expected = derivations.get(fact, [])
+ actual = explanation.derivations
+ assert len(actual) == len(expected), (
+ f"derivation count mismatch for {atom_text(fact)}\nseed={seed}\nstage={stage}\nrules={[rule_text(r) for r in rules]}\nevents={events}\n"
+ f"expected={expected}\nactual={[(d.rule_id, d.premises, d.bindings) for d in actual]}"
+ )
+ for (rule_id, premises, bindings), derivation in zip(expected, actual):
+ assert derivation.rule_id == rule_id
+ assert derivation.conclusion == atom_text(fact)
+ assert derivation.premises == tuple(atom_text(p) for p in premises)
+ assert derivation.bindings == bindings
+ expected_ids = tuple(sorted(sid for sid, fact_of in supports.items() if fact_of == fact))
+ assert explanation.explicit_support_ids == expected_ids, (
+ f"explicit support mismatch for {atom_text(fact)}\nseed={seed}\nstage={stage}\nevents={events}"
+ )
+
+
+# --------------------------------------------------------------------------
+# Differential loop
+# --------------------------------------------------------------------------
+
+def run_seed(seed):
+ rng = random.Random(seed)
+ rules = generate_rules(rng)
+ session = build_session(rules)
+
+ supports = {}
+ catalog = {}
+ counter = itertools.count()
+ for _ in range(15):
+ sid = f"s{next(counter)}"
+ atom = random_ground_atom(rng)
+ catalog[sid] = atom
+ supports[sid] = atom
+ delta = session.apply(
+ assertions=[FactSupport(sid, atom_text(atom)) for sid, atom in supports.items()]
+ )
+ assert delta.version == 1
+ assert delta.added_supports == tuple(
+ FactSupport(sid, atom_text(supports[sid])) for sid in sorted(supports)
+ )
+ assert delta.removed_supports == ()
+
+ events = []
+ compare_session(session, rules, supports, seed, "initial", events)
+ closure = oracle_closure(rules, set(supports.values()))
+ version = 1
+
+ for batch_index in range(60):
+ assertions, retractions, invalid = generate_batch(rng, catalog, supports, counter)
+ batch = (assertions, retractions, invalid)
+ if invalid is not None:
+ before = (session.version, session.facts)
+ with pytest.raises(ValidationError):
+ session.apply(
+ assertions=[
+ FactSupport(sid, atom_text(fact))
+ for sid, fact in assertions + [invalid]
+ ],
+ retractions=list(retractions),
+ )
+ assert (session.version, session.facts) == before
+ events.append((batch, "rejected"))
+ continue
+ delta = session.apply(
+ assertions=[FactSupport(sid, atom_text(fact)) for sid, fact in assertions],
+ retractions=list(retractions),
+ )
+ new_supports = {key: value for key, value in supports.items() if key not in retractions}
+ new_supports.update(assertions)
+ new_closure = oracle_closure(rules, set(new_supports.values()))
+
+ added_facts = new_closure - closure
+ removed_facts = closure - new_closure
+ added_support_ids = tuple(sorted(set(new_supports) - set(supports)))
+ removed_support_ids = tuple(sorted(set(supports) - set(new_supports)))
+ changed = bool(
+ added_facts or removed_facts or added_support_ids or removed_support_ids
+ )
+ if changed:
+ version += 1
+
+ stage = f"batch {batch_index}"
+ assert delta.version == version, (
+ f"version mismatch\nseed={seed}\nstage={stage}\nevents={events}\nbatch={batch}"
+ )
+ assert delta.added_facts == frozenset(atom_text(fact) for fact in added_facts), (
+ f"added facts mismatch\nseed={seed}\nstage={stage}\nevents={events}\nbatch={batch}"
+ f"\nexpected={sorted(atom_text(fact) for fact in added_facts)}"
+ f"\nactual={sorted(delta.added_facts)}"
+ )
+ assert delta.removed_facts == frozenset(atom_text(fact) for fact in removed_facts), (
+ f"removed facts mismatch\nseed={seed}\nstage={stage}\nevents={events}\nbatch={batch}"
+ f"\nexpected={sorted(atom_text(fact) for fact in removed_facts)}"
+ f"\nactual={sorted(delta.removed_facts)}"
+ )
+ assert delta.added_supports == tuple(
+ FactSupport(sid, atom_text(new_supports[sid])) for sid in added_support_ids
+ ), f"added supports mismatch\nseed={seed}\nstage={stage}\nevents={events}\nbatch={batch}"
+ assert delta.removed_supports == tuple(
+ FactSupport(sid, atom_text(supports[sid])) for sid in removed_support_ids
+ ), f"removed supports mismatch\nseed={seed}\nstage={stage}\nevents={events}\nbatch={batch}"
+
+ supports = new_supports
+ closure = new_closure
+ events.append((batch, "applied"))
+ compare_session(session, rules, supports, seed, stage, events)
+
+
[email protected]("seed", range(20))
+def test_differential_against_oracle(seed):
+ run_seed(seed)
+
+
+# --------------------------------------------------------------------------
+# Metamorphic checks
+# --------------------------------------------------------------------------
+
+def logical_state(session):
+ return (
+ session.facts,
+ {fact: session.explain(fact).derivations for fact in session.facts},
+ {fact: session.explain(fact).explicit_support_ids for fact in session.facts},
+ )
+
+
+def test_metamorphic_order_independence():
+ rng = random.Random(11)
+ rules = generate_rules(rng)
+ initial = [(f"s{index}", random_ground_atom(rng)) for index in range(10)]
+
+ session_a = build_session(rules)
+ session_a.apply(
+ assertions=[FactSupport(sid, atom_text(atom)) for sid, atom in initial]
+ )
+
+ shuffler = random.Random(99)
+ shuffled_rules = list(rules)
+ shuffler.shuffle(shuffled_rules)
+ shuffled_initial = list(initial)
+ shuffler.shuffle(shuffled_initial)
+ session_b = build_session(tuple(shuffled_rules))
+ session_b.apply(
+ assertions=[FactSupport(sid, atom_text(atom)) for sid, atom in shuffled_initial]
+ )
+
+ # Replay identical batches on both sessions.
+ replay_rng = random.Random(5)
+ catalog = dict(initial)
+ supports = dict(initial)
+ counter = itertools.count(10)
+ for _ in range(15):
+ assertions, retractions, _invalid = generate_batch(replay_rng, catalog, supports, counter)
+ batch_assertions = [FactSupport(sid, atom_text(fact)) for sid, fact in assertions]
+ session_a.apply(assertions=batch_assertions, retractions=list(retractions))
+ session_b.apply(assertions=batch_assertions, retractions=list(retractions))
+ supports = {key: value for key, value in supports.items() if key not in retractions}
+ supports.update(assertions)
+
+ assert session_a.facts == session_b.facts
+ for fact in session_a.facts:
+ assert session_a.explain(fact).derivations == session_b.explain(fact).derivations
+ assert (
+ session_a.explain(fact).explicit_support_ids
+ == session_b.explain(fact).explicit_support_ids
+ )
+
+
+def test_metamorphic_add_then_retract_restores_state():
+ rng = random.Random(3)
+ rules = generate_rules(rng)
+ session = build_session(rules)
+ initial = [(f"s{index}", random_ground_atom(rng)) for index in range(8)]
+ session.apply(
+ assertions=[FactSupport(sid, atom_text(atom)) for sid, atom in initial]
+ )
+
+ before = logical_state(session)
+ session.apply(assertions=[FactSupport("probe", atom_text(("P1", ("a", "b"))))])
+ session.apply(retractions=["probe"])
+ after = logical_state(session)
+
+ assert before == after
\ No newline at end of file