Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(reasoning): export and restore truth maintenance checkpoints

江俊杰8f7ce45d143b
diff --git a/semantica/reasoning/truth_maintenance.py b/semantica/reasoning/truth_maintenance.py
index f12a4020..e1efa170 100644
--- a/semantica/reasoning/truth_maintenance.py
+++ b/semantica/reasoning/truth_maintenance.py
@@ -15,6 +15,7 @@ from collections.abc import Iterable
from typing import Dict, FrozenSet, List, Set, Tuple
from ..utils.exceptions import ProcessingError, ValidationError
+from ._truth_maintenance_checkpoint import decode_checkpoint, encode_checkpoint
from ._truth_maintenance_validation import (
_RuleSnapshot,
build_rule_snapshots,
@@ -125,9 +126,7 @@ class _SessionState:
)
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)
+ 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."""
@@ -209,6 +208,61 @@ class TruthMaintenanceSession:
)
return FactExplanation(canonical, True, support_ids, tuple(derivations))
+ # -- checkpoints ------------------------------------------------------
+
+ def to_checkpoint(self) -> Dict[str, object]:
+ """Return a JSON-compatible, detached v1 checkpoint of this session.
+
+ The payload contains captured rules, the complete support catalog,
+ active support IDs, and the committed version. It never contains
+ derived facts or internal indexes. The session state is not read
+ through caller-owned :class:`Rule` objects and no matcher is invoked.
+ """
+ state = self._state
+ return encode_checkpoint(
+ rules=self._rules,
+ support_catalog=state.support_catalog,
+ active_support_ids=state.active_supports,
+ session_version=self._version,
+ )
+
+ @classmethod
+ def from_checkpoint(cls, payload: object) -> TruthMaintenanceSession:
+ """Restore a new session from a fixed v1 checkpoint payload.
+
+ Structural, rule, fact, arity, and closure rebuilding must all
+ succeed before a session is returned. On failure, neither the input
+ payload nor an existing source session is modified.
+ """
+ try:
+ decoded = decode_checkpoint(payload)
+ session = cls(rules=decoded.rules)
+ canonical_pairs, new_arities = session._validate_assertions(
+ list(decoded.catalog_supports), []
+ )
+
+ candidate = _SessionState()
+ candidate.support_catalog = dict(canonical_pairs)
+ candidate.arities = dict(session._state.arities)
+ candidate.arities.update(new_arities)
+ session._state = candidate
+
+ session.apply(
+ assertions=[
+ FactSupport(support_id, candidate.support_catalog[support_id])
+ for support_id in decoded.active_support_ids
+ ]
+ )
+ session._version = decoded.session_version
+ return session
+ except (ValidationError, ProcessingError):
+ raise
+ except Exception as exc:
+ raise ProcessingError(
+ "truth maintenance checkpoint restore failed",
+ validation_context={},
+ ) from exc
+
# -- batched updates --------------------------------------------------
def apply(
@@ -245,9 +299,7 @@ class TruthMaintenanceSession:
if rid in self._state.active_supports
]
if not effective_assertions and not effective_retractions:
- return MaintenanceDelta(
- self._version, frozenset(), frozenset(), (), ()
- )
+ return MaintenanceDelta(self._version, frozenset(), frozenset(), (), ())
try:
candidate = self._state.clone()
@@ -376,9 +428,7 @@ class TruthMaintenanceSession:
if not body_predicates & affected:
continue
conclusions = candidate.remove_rule_derivations(snapshot.rule_id)
- for premises, bindings, conclusion in self._match_rule(
- snapshot, candidate
- ):
+ for premises, bindings, conclusion in self._match_rule(snapshot, candidate):
candidate.add_derivation(
Derivation(snapshot.rule_id, conclusion, premises, bindings)
)
@@ -440,15 +490,8 @@ class TruthMaintenanceSession:
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(), (), ()
- )
+ 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(
@@ -489,9 +532,7 @@ def _match_snapshot(
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
- )
+ substituted = tuple(bindings.get(term, term) for term in conclusion_terms)
results.append(
(
tuple(premises),
@@ -559,4 +600,4 @@ def _coerce_id_iterable(value: object) -> List[str]:
"retraction entries must be non-empty support-id strings",
validation_context={"entry": repr(item)[:64]},
)
- return items
\ No newline at end of file
+ return items
diff --git a/tests/reasoning/test_truth_maintenance_checkpoint.py b/tests/reasoning/test_truth_maintenance_checkpoint.py
new file mode 100644
index 00000000..96524e76
--- /dev/null
+++ b/tests/reasoning/test_truth_maintenance_checkpoint.py
@@ -0,0 +1,414 @@
+"""Public checkpoint export and restore tests for TruthMaintenanceSession."""
+
+import copy
+import json
+
+import pytest
+
+from semantica.reasoning import (
+ Derivation,
+ FactSupport,
+ Rule,
+ TruthMaintenanceSession,
+ TruthMaintenanceSnapshot,
+)
+from semantica.utils.exceptions import ProcessingError, ValidationError
+
+CHECKPOINT_V1_JSON = """{
+ "format_version": 1,
+ "session_version": 4,
+ "rules": [
+ {
+ "rule_id": "employment-eligibility",
+ "conditions": ["Employed(?x)"],
+ "conclusion": "Eligible(?x)"
+ }
+ ],
+ "support_catalog": [
+ {"support_id": "document-v1", "fact": "Employed(Alice)"},
+ {"support_id": "document-v2", "fact": "Employed(Alice)"}
+ ],
+ "active_support_ids": ["document-v2"]
+}"""
+
+NORMALIZED_CHECKPOINT_V1 = {
+ "format_version": 1,
+ "session_version": 4,
+ "rules": [
+ {
+ "rule_id": "employment-eligibility",
+ "conditions": ["Employed(?x)"],
+ "conclusion": "Eligible(?x)",
+ }
+ ],
+ "support_catalog": [
+ {"support_id": "document-v1", "fact": "Employed(Alice)"},
+ {"support_id": "document-v2", "fact": "Employed(Alice)"},
+ ],
+ "active_support_ids": ["document-v2"],
+}
+
+
+def checkpoint_payload(rules, catalog, active, session_version):
+ return {
+ "format_version": 1,
+ "session_version": session_version,
+ "rules": [
+ {
+ "rule_id": rule_id,
+ "conditions": list(conditions),
+ "conclusion": conclusion,
+ }
+ for rule_id, conditions, conclusion in rules
+ ],
+ "support_catalog": [
+ {"support_id": support_id, "fact": fact}
+ for support_id, fact in sorted(catalog.items())
+ ],
+ "active_support_ids": sorted(active),
+ }
+
+
+def test_restore_preserves_two_source_withdrawals():
+ original = TruthMaintenanceSession(
+ rules=[Rule("eligibility", "Eligibility", ["Employed(?x)"], "Eligible(?x)")]
+ )
+ original.apply(
+ assertions=[
+ FactSupport("doc-1", "Employed(Alice)"),
+ FactSupport("doc-2", "Employed(Alice)"),
+ ]
+ )
+ restored = TruthMaintenanceSession.from_checkpoint(
+ json.loads(json.dumps(original.to_checkpoint()))
+ )
+
+ assert restored.snapshot() == original.snapshot()
+ assert restored.explain("Eligible(Alice)") == original.explain("Eligible(Alice)")
+ for source in ("doc-1", "doc-2"):
+ assert restored.apply(retractions=[source]) == original.apply(
+ retractions=[source]
+ )
+ assert restored.snapshot() == original.snapshot()
+ assert restored.explain("Eligible(Alice)") == original.explain(
+ "Eligible(Alice)"
+ )
+ assert restored.facts == frozenset()
+
+
+def test_checkpoint_survives_repeated_json_round_trips():
+ original = TruthMaintenanceSession(
+ rules=[Rule("employment", "Employment", ["Employed(?x)"], "Eligible(?x)")]
+ )
+ original.apply(
+ assertions=[
+ FactSupport("doc-1", "Employed(Alice)"),
+ FactSupport("doc-2", "Employed(Alice)"),
+ ]
+ )
+ payload = original.to_checkpoint()
+
+ for _ in range(3):
+ restored = TruthMaintenanceSession.from_checkpoint(
+ json.loads(json.dumps(payload))
+ )
+ assert restored.snapshot() == original.snapshot()
+ assert restored.explain("Eligible(Alice)") == original.explain(
+ "Eligible(Alice)"
+ )
+ assert restored.to_checkpoint() == payload
+
+
+def test_fixed_v1_fixture_restores_and_reexports_normalized_payload():
+ restored = TruthMaintenanceSession.from_checkpoint(json.loads(CHECKPOINT_V1_JSON))
+
+ assert restored.version == 4
+ assert restored.snapshot() == TruthMaintenanceSnapshot(
+ version=4,
+ facts=frozenset({"Employed(Alice)", "Eligible(Alice)"}),
+ active_supports=(FactSupport("document-v2", "Employed(Alice)"),),
+ )
+ assert restored.explain("Eligible(Alice)").derivations == (
+ Derivation(
+ rule_id="employment-eligibility",
+ conclusion="Eligible(Alice)",
+ premises=("Employed(Alice)",),
+ bindings=(("?x", "Alice"),),
+ ),
+ )
+ assert restored.to_checkpoint() == NORMALIZED_CHECKPOINT_V1
+
+
+def test_empty_sessions_restore_with_version_zero():
+ no_rules = TruthMaintenanceSession.from_checkpoint(
+ {
+ "format_version": 1,
+ "session_version": 0,
+ "rules": [],
+ "support_catalog": [],
+ "active_support_ids": [],
+ }
+ )
+ assert no_rules.snapshot().version == 0
+ assert no_rules.facts == frozenset()
+ assert no_rules.to_checkpoint() == {
+ "format_version": 1,
+ "session_version": 0,
+ "rules": [],
+ "support_catalog": [],
+ "active_support_ids": [],
+ }
+
+ rules_only = TruthMaintenanceSession.from_checkpoint(
+ checkpoint_payload(
+ rules=[("ab", ["A(?x)"], "B(?x)")],
+ catalog={},
+ active=[],
+ session_version=0,
+ )
+ )
+ assert rules_only.snapshot().version == 0
+ assert rules_only.facts == frozenset()
+ assert rules_only.to_checkpoint()["rules"] == [
+ {"rule_id": "ab", "conditions": ["A(?x)"], "conclusion": "B(?x)"}
+ ]
+
+
+def test_all_supports_withdrawn_restores_catalog_and_positive_version():
+ original = TruthMaintenanceSession(rules=[])
+ original.apply(assertions=[FactSupport("retired", "Archived(Alice)")])
+ original.apply(retractions=["retired"])
+ payload = original.to_checkpoint()
+
+ restored = TruthMaintenanceSession.from_checkpoint(copy.deepcopy(payload))
+
+ assert restored.snapshot() == TruthMaintenanceSnapshot(
+ version=2,
+ facts=frozenset(),
+ active_supports=(),
+ )
+ assert restored.to_checkpoint() == payload
+ assert restored.to_checkpoint()["support_catalog"] == [
+ {"support_id": "retired", "fact": "Archived(Alice)"}
+ ]
+
+
+def test_retired_support_binding_and_arity_survive_restore():
+ original = TruthMaintenanceSession(rules=[])
+ original.apply(assertions=[FactSupport("retired", "Q(a)")])
+ original.apply(retractions=["retired"])
+ restored = TruthMaintenanceSession.from_checkpoint(
+ json.loads(json.dumps(original.to_checkpoint()))
+ )
+
+ for invalid_support in (
+ FactSupport("retired", "Q(b)"),
+ FactSupport("new-id", "Q(a, b)"),
+ ):
+ with pytest.raises(ValidationError):
+ restored.apply(assertions=[invalid_support])
+
+ assert restored.apply(
+ assertions=[FactSupport("retired", "Q(a)")]
+ ) == original.apply(assertions=[FactSupport("retired", "Q(a)")])
+ assert restored.facts == frozenset({"Q(a)"})
+
+
+def test_zero_arity_predicates_survive_restore():
+ original = TruthMaintenanceSession(rules=[Rule("go", "Go", ["Ready()"], "Go()")])
+ original.apply(assertions=[FactSupport("ready", "Ready()")])
+ restored = TruthMaintenanceSession.from_checkpoint(
+ json.loads(json.dumps(original.to_checkpoint()))
+ )
+
+ assert restored.snapshot() == original.snapshot()
+ assert restored.explain("Go()") == original.explain("Go()")
+ with pytest.raises(ValidationError):
+ restored.apply(assertions=[FactSupport("bad", "Go(a)")])
+ assert restored.apply(assertions=[FactSupport("go", "Go()")]) == original.apply(
+ assertions=[FactSupport("go", "Go()")]
+ )
+
+
+def test_rule_only_predicate_arity_survives_restore_without_catalog_facts():
+ original = TruthMaintenanceSession(rules=[Rule("ab", "AB", ["A(?x)"], "B(?x)")])
+ restored = TruthMaintenanceSession.from_checkpoint(original.to_checkpoint())
+
+ with pytest.raises(ValidationError):
+ restored.apply(assertions=[FactSupport("bad-head", "B(a, b)")])
+ with pytest.raises(ValidationError):
+ restored.apply(assertions=[FactSupport("bad-body", "A(a, b)")])
+
+ restored.apply(assertions=[FactSupport("source", "A(a)")])
+ assert restored.facts == frozenset({"A(a)", "B(a)"})
+
+
+ "payload",
+ [
+ checkpoint_payload(
+ rules=[("bad", ["Not an atom"], "B(?x)")],
+ catalog={},
+ active=[],
+ session_version=0,
+ ),
+ checkpoint_payload(
+ rules=[("bad", ["A(?x)"], "Not an atom")],
+ catalog={},
+ active=[],
+ session_version=0,
+ ),
+ checkpoint_payload(
+ rules=[],
+ catalog={"source": "Not an atom"},
+ active=["source"],
+ session_version=1,
+ ),
+ checkpoint_payload(
+ rules=[],
+ catalog={"source": "A(?x)"},
+ active=["source"],
+ session_version=1,
+ ),
+ checkpoint_payload(
+ rules=[("unbound", ["A(?x)"], "B(?y)")],
+ catalog={},
+ active=[],
+ session_version=0,
+ ),
+ checkpoint_payload(
+ rules=[
+ ("ab", ["A(?x)"], "B(?x)"),
+ ("ba", ["B(?x)"], "A(?x)"),
+ ],
+ catalog={},
+ active=[],
+ session_version=0,
+ ),
+ checkpoint_payload(
+ rules=[
+ ("ab", ["A(?x)"], "B(?x)"),
+ ("bc", ["B(?x)"], "C(?x)"),
+ ("ca", ["C(?x)"], "A(?x)"),
+ ],
+ catalog={},
+ active=[],
+ session_version=0,
+ ),
+ checkpoint_payload(
+ rules=[
+ ("a1", ["A(?x)"], "B(?x)"),
+ ("a2", ["A(?x, ?y)"], "C(?x, ?y)"),
+ ],
+ catalog={},
+ active=[],
+ session_version=0,
+ ),
+ checkpoint_payload(
+ rules=[("ab", ["A(?x)"], "B(?x)")],
+ catalog={"active": "A(a)", "inactive": "A(a, b)"},
+ active=["active"],
+ session_version=1,
+ ),
+ ],
+ ids=[
+ "invalid-condition",
+ "invalid-conclusion",
+ "invalid-fact",
+ "variable-fact",
+ "unbound-head-variable",
+ "direct-cycle",
+ "indirect-cycle",
+ "rule-arity-conflict",
+ "inactive-fact-arity-conflict",
+ ],
+)
+def test_semantic_rejection_leaves_payload_unchanged(payload):
+ before = copy.deepcopy(payload)
+ with pytest.raises(ValidationError):
+ TruthMaintenanceSession.from_checkpoint(payload)
+ assert payload == before
+
+
+def test_export_uses_captured_rules_not_caller_rule_mutation():
+ caller_rule = Rule("captured", "Captured", ["A(?x)"], "B(?x)")
+ session = TruthMaintenanceSession(rules=[caller_rule])
+
+ caller_rule.rule_id = "mutated-id"
+ caller_rule.name = "Mutated"
+ caller_rule.conditions = ["Changed(?x)"]
+ caller_rule.conclusion = "Changed(?x)"
+
+ payload = session.to_checkpoint()
+ assert payload["rules"] == [
+ {"rule_id": "captured", "conditions": ["A(?x)"], "conclusion": "B(?x)"}
+ ]
+
+ restored = TruthMaintenanceSession.from_checkpoint(payload)
+ restored.apply(assertions=[FactSupport("source", "A(a)")])
+ assert restored.facts == frozenset({"A(a)", "B(a)"})
+
+
+def test_payload_and_restored_session_are_isolated_in_both_directions():
+ original = TruthMaintenanceSession(rules=[Rule("ab", "AB", ["A(?x)"], "B(?x)")])
+ original.apply(assertions=[FactSupport("source", "A(a)")])
+ expected_payload = original.to_checkpoint()
+ before_snapshot = original.snapshot()
+ payload = copy.deepcopy(expected_payload)
+ restored = TruthMaintenanceSession.from_checkpoint(payload)
+
+ payload["rules"][0]["rule_id"] = "mutated"
+ payload["rules"][0]["conditions"].append("Injected(?x)")
+ payload["support_catalog"][0]["fact"] = "Injected(a)"
+ payload["active_support_ids"].append("source")
+
+ assert original.to_checkpoint() == expected_payload
+ assert original.snapshot() == before_snapshot
+ assert restored.to_checkpoint() == expected_payload
+ assert restored.snapshot() == before_snapshot
+
+ restored.apply(assertions=[FactSupport("second", "A(b)")])
+ assert payload == {
+ "format_version": 1,
+ "session_version": 1,
+ "rules": [
+ {
+ "rule_id": "mutated",
+ "conditions": ["A(?x)", "Injected(?x)"],
+ "conclusion": "B(?x)",
+ }
+ ],
+ "support_catalog": [
+ {"support_id": "source", "fact": "Injected(a)"},
+ ],
+ "active_support_ids": ["source", "source"],
+ }
+
+
+def test_matcher_failure_is_wrapped_without_mutating_input_or_source(
+ monkeypatch,
+):
+ original = TruthMaintenanceSession(rules=[Rule("ab", "AB", ["A(?x)"], "B(?x)")])
+ original.apply(assertions=[FactSupport("source", "A(a)")])
+ before_snapshot = original.snapshot()
+ payload = original.to_checkpoint()
+ before_payload = copy.deepcopy(payload)
+
+ def fail_matcher(*args, **kwargs):
+ raise RuntimeError("matcher unavailable")
+
+ monkeypatch.setattr(TruthMaintenanceSession, "_match_rule", fail_matcher)
+
+ assert original.to_checkpoint() == before_payload
+ with pytest.raises(ProcessingError) as error:
+ TruthMaintenanceSession.from_checkpoint(copy.deepcopy(payload))
+
+ assert isinstance(error.value.__cause__, RuntimeError)
+ assert str(error.value.__cause__) == "matcher unavailable"
+ assert original.to_checkpoint() == before_payload
+ assert original.snapshot() == before_snapshot
+ assert payload == before_payload
+
+ monkeypatch.undo()
+ restored = TruthMaintenanceSession.from_checkpoint(payload)
+ assert restored.snapshot() == before_snapshot