Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
test(reasoning): verify checkpoint continuation across restarts
江俊杰bfd4fb7cc216
diff --git a/tests/reasoning/test_truth_maintenance_checkpoint.py b/tests/reasoning/test_truth_maintenance_checkpoint.pyindex 96524e76..2fbef913 100644--- a/tests/reasoning/test_truth_maintenance_checkpoint.py+++ b/tests/reasoning/test_truth_maintenance_checkpoint.py@@ -2,9 +2,15 @@import copyimport json+import os+import subprocess+import sys+from dataclasses import asdict+from pathlib import Pathimport pytest+import semanticafrom semantica.reasoning import (Derivation,FactSupport,@@ -31,6 +37,111 @@ CHECKPOINT_V1_JSON = """{"active_support_ids": ["document-v2"]}"""+REPO_ROOT = Path(__file__).resolve().parents[2]++SUBPROCESS_CHILD_CODE = r"""+import json+import os+import sys+from dataclasses import asdict++from semantica.reasoning import FactSupport, TruthMaintenanceSession+from semantica.utils.exceptions import ValidationError++ROOT = __ROOT__+import semantica++if not semantica.__file__.startswith(ROOT):+ raise AssertionError(semantica.__file__)++payload = json.load(sys.stdin)+session = TruthMaintenanceSession.from_checkpoint(payload)+++def snapshot():+ value = session.snapshot()+ return {+ "version": value.version,+ "facts": sorted(value.facts),+ "active_supports": [asdict(support) for support in value.active_supports],+ }+++def explanations():+ return {+ fact: asdict(session.explain(fact))+ for fact in ("Employed(Alice)", "Eligible(Alice)", "Q(a)")+ }+++def delta(value):+ return {+ "version": value.version,+ "added_facts": sorted(value.added_facts),+ "removed_facts": sorted(value.removed_facts),+ "added_supports": [asdict(support) for support in value.added_supports],+ "removed_supports": [asdict(support) for support in value.removed_supports],+ }+++def rejected(assertion):+ before = snapshot()+ try:+ session.apply(assertions=[FactSupport(*assertion)])+ except ValidationError:+ return {+ "error": "ValidationError",+ "before": before,+ "after": snapshot(),+ "explanations": explanations(),+ }+ raise AssertionError("expected ValidationError")+++steps = []+steps.append({"reject-rebind": rejected(("retired", "Q(b)"))})+value = session.apply(assertions=[FactSupport("retired", "Q(a)")])+steps.append({+ "reactivate": {+ "delta": delta(value),+ "state": snapshot(),+ "explanations": explanations(),+ }+})+value = session.apply(retractions=["doc-1"])+steps.append({+ "withdraw-first": {+ "delta": delta(value),+ "state": snapshot(),+ "explanations": explanations(),+ }+})+value = session.apply(retractions=["doc-2"])+steps.append({+ "withdraw-second": {+ "delta": delta(value),+ "state": snapshot(),+ "explanations": explanations(),+ }+})+steps.append({"reject-arity": rejected(("new-id", "Q(a, b)"))})+value = session.apply()+steps.append({+ "noop": {+ "delta": delta(value),+ "state": snapshot(),+ "explanations": explanations(),+ }+})++print(json.dumps({+ "module_path": semantica.__file__,+ "hash_seed": os.environ["PYTHONHASHSEED"],+ "initial": {"state": snapshot(), "explanations": explanations()},+ "steps": steps,+}, sort_keys=True))+""".replace("__ROOT__", repr(str(REPO_ROOT)))+NORMALIZED_CHECKPOINT_V1 = {"format_version": 1,"session_version": 4,@@ -69,6 +180,266 @@ def checkpoint_payload(rules, catalog, active, session_version):}+def assert_sessions_continue_identically(original, restored, *, operation, facts=()):+ original_delta = operation(original)+ restored_delta = operation(restored)+ assert restored_delta == original_delta+ assert original.snapshot() == restored.snapshot()+ assert original.to_checkpoint() == restored.to_checkpoint()+ for fact in facts:+ assert original.explain(fact) == restored.explain(fact)+ return original_delta+++def assert_rejected_without_state_change(original, restored, operation):+ original_before = (+ original.snapshot(),+ original.to_checkpoint(),+ original.version,+ )+ restored_before = (+ restored.snapshot(),+ restored.to_checkpoint(),+ restored.version,+ )+ with pytest.raises(ValidationError):+ operation(original)+ with pytest.raises(ValidationError):+ operation(restored)+ assert (+ original.snapshot(),+ original.to_checkpoint(),+ original.version,+ ) == original_before+ assert (+ restored.snapshot(),+ restored.to_checkpoint(),+ restored.version,+ ) == restored_before+++def alternative_derivation_session():+ session = TruthMaintenanceSession(+ rules=[+ Rule("ac", "AC", ["A(?x)"], "C(?x)"),+ Rule("bc", "BC", ["B(?x)"], "C(?x)"),+ ]+ )+ session.apply(+ assertions=[+ FactSupport("a1", "A(a)"),+ FactSupport("a2", "A(b)"),+ FactSupport("b", "B(a)"),+ FactSupport("c", "C(a)"),+ ]+ )+ return session+++def compare_withdrawal_order(session, restored, first_source):+ relevant_facts = ("A(a)", "A(b)", "B(a)", "C(a)", "C(b)")+ first_fact = session_snapshot_fact(session, first_source)+ first = assert_sessions_continue_identically(+ session,+ restored,+ operation=lambda item: item.apply(retractions=[first_source]),+ facts=relevant_facts,+ )+ assert first.removed_supports == (FactSupport(first_source, first_fact),)++ second_source = "b" if first_source == "a1" else "a1"+ second_fact = session_snapshot_fact(session, second_source)+ second = assert_sessions_continue_identically(+ session,+ restored,+ operation=lambda item: item.apply(retractions=[second_source]),+ facts=relevant_facts,+ )+ assert second.removed_supports == (FactSupport(second_source, second_fact),)+++def session_snapshot_fact(session, support_id):+ for support in session.snapshot().active_supports:+ if support.support_id == support_id:+ return support.fact+ raise AssertionError(f"missing active support {support_id}")+++def test_alternative_derivations_and_multiple_matches_survive_restore():+ original_a_first = alternative_derivation_session()+ original_b_first = alternative_derivation_session()+ restored_a_first = TruthMaintenanceSession.from_checkpoint(+ json.loads(json.dumps(original_a_first.to_checkpoint()))+ )+ restored_b_first = TruthMaintenanceSession.from_checkpoint(+ json.loads(json.dumps(original_b_first.to_checkpoint()))+ )++ assert original_a_first.explain("C(a)").derivations == (+ Derivation("ac", "C(a)", ("A(a)",), (("?x", "a"),)),+ Derivation("bc", "C(a)", ("B(a)",), (("?x", "a"),)),+ )+ assert original_a_first.explain("C(a)").explicit_support_ids == ("c",)++ compare_withdrawal_order(original_a_first, restored_a_first, "a1")+ compare_withdrawal_order(original_b_first, restored_b_first, "b")++ assert original_a_first.snapshot() == original_b_first.snapshot()+ assert original_a_first.to_checkpoint() == original_b_first.to_checkpoint()+++def test_replacement_and_noop_semantics_survive_restore():+ original = TruthMaintenanceSession(rules=[])+ original.apply(assertions=[FactSupport("old", "A(x)")])+ restored = TruthMaintenanceSession.from_checkpoint(+ json.loads(json.dumps(original.to_checkpoint()))+ )++ empty = assert_sessions_continue_identically(+ original,+ restored,+ operation=lambda item: item.apply(),+ facts=("A(x)",),+ )+ assert empty.version == 1+ assert empty.added_facts == empty.removed_facts == frozenset()++ duplicate = assert_sessions_continue_identically(+ original,+ restored,+ operation=lambda item: item.apply(+ assertions=[FactSupport("old", "A(x)"), FactSupport("old", "A(x)")]+ ),+ facts=("A(x)",),+ )+ assert duplicate.version == 1++ unknown = assert_sessions_continue_identically(+ original,+ restored,+ operation=lambda item: item.apply(retractions=["unknown"]),+ facts=("A(x)",),+ )+ assert unknown.version == 1++ retired = assert_sessions_continue_identically(+ original,+ restored,+ operation=lambda item: item.apply(assertions=[FactSupport("retired", "R(a)")]),+ facts=("A(x)", "R(a)"),+ )+ assert retired.version == 2+ assert retired.added_supports == (FactSupport("retired", "R(a)"),)++ assert_sessions_continue_identically(+ original,+ restored,+ operation=lambda item: item.apply(retractions=["retired"]),+ facts=("A(x)", "R(a)"),+ )+ inactive = assert_sessions_continue_identically(+ original,+ restored,+ operation=lambda item: item.apply(retractions=["retired"]),+ facts=("A(x)",),+ )+ assert inactive.version == 3++ replacement = assert_sessions_continue_identically(+ original,+ restored,+ operation=lambda item: item.apply(+ assertions=[FactSupport("new", "A(x)")],+ retractions=["old"],+ ),+ facts=("A(x)",),+ )+ assert replacement.version == 4+ assert replacement.added_supports == (FactSupport("new", "A(x)"),)+ assert replacement.removed_supports == (FactSupport("old", "A(x)"),)+ assert original.facts == frozenset({"A(x)"})++ assert_rejected_without_state_change(+ original,+ restored,+ operation=lambda item: item.apply(+ assertions=[FactSupport("new", "A(y)")],+ retractions=["new"],+ ),+ )++ assert_rejected_without_state_change(+ original,+ restored,+ operation=lambda item: item.apply(+ assertions=[+ FactSupport("ghost", "Z(a)"),+ FactSupport("new", "A(y)"),+ ]+ ),+ )+ valid_ghost = assert_sessions_continue_identically(+ original,+ restored,+ operation=lambda item: item.apply(assertions=[FactSupport("ghost", "Z(a, b)")]),+ facts=("A(x)", "Z(a, b)"),+ )+ assert valid_ghost.version == 5+ assert valid_ghost.added_facts == frozenset({"Z(a, b)"})+++def test_condition_order_duplicate_conditions_and_whitespace_binding():+ original = TruthMaintenanceSession(+ rules=[+ Rule("ba", "BA", ["B(?x)", "A(?y)"], "C(?x, ?y)"),+ Rule("duplicate", "Duplicate", ["A(?x)", "A(?x)"], "D(?x)"),+ ]+ )+ original.apply(+ assertions=[+ FactSupport("b", "B(w)"),+ FactSupport("a", "A(v)"),+ FactSupport("a-ground", "A(a)"),+ ]+ )+ restored = TruthMaintenanceSession.from_checkpoint(+ json.loads(json.dumps(original.to_checkpoint()))+ )++ assert (+ restored.explain("C(w, v)").derivations+ == original.explain("C(w, v)").derivations+ )+ assert restored.explain("C(w, v)").derivations == (+ Derivation(+ rule_id="ba",+ conclusion="C(w, v)",+ premises=("B(w)", "A(v)"),+ bindings=(("?x", "w"), ("?y", "v")),+ ),+ )+ assert restored.explain("D(a)").derivations == (+ Derivation(+ rule_id="duplicate",+ conclusion="D(a)",+ premises=("A(a)", "A(a)"),+ bindings=(("?x", "a"),),+ ),+ )++ whitespace_session = TruthMaintenanceSession(rules=[])+ whitespace_session.apply(assertions=[FactSupport("source", "A( a )")])+ whitespace_session.apply(retractions=["source"])+ whitespace_restored = TruthMaintenanceSession.from_checkpoint(+ json.loads(json.dumps(whitespace_session.to_checkpoint()))+ )+ delta = whitespace_restored.apply(assertions=[FactSupport("source", "A( a )")])+ assert delta.added_facts == frozenset({"A(a)"})+ assert whitespace_restored.snapshot().active_supports == (+ FactSupport("source", "A(a)"),+ )++def test_restore_preserves_two_source_withdrawals():original = TruthMaintenanceSession(rules=[Rule("eligibility", "Eligibility", ["Employed(?x)"], "Eligible(?x)")]@@ -412,3 +783,154 @@ def test_matcher_failure_is_wrapped_without_mutating_input_or_source(monkeypatch.undo()restored = TruthMaintenanceSession.from_checkpoint(payload)assert restored.snapshot() == before_snapshot+++def test_payload_nested_modification_never_reaches_sessions_after_apply():+ original = TruthMaintenanceSession(rules=[Rule("ab", "AB", ["A(?x)"], "B(?x)")])+ original.apply(assertions=[FactSupport("source", "A(a)")])+ expected_payload = original.to_checkpoint()+ 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")++ original_delta = original.apply(assertions=[FactSupport("second", "A(b)")])+ restored_delta = restored.apply(assertions=[FactSupport("second", "A(b)")])+ assert original_delta == restored_delta+ assert original.to_checkpoint()["rules"] == expected_payload["rules"]+ assert restored.to_checkpoint()["rules"] == expected_payload["rules"]+ 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_checkpoint_continues_in_a_fresh_process():+ original = TruthMaintenanceSession(+ rules=[Rule("eligibility", "Eligibility", ["Employed(?x)"], "Eligible(?x)")]+ )+ original.apply(+ assertions=[+ FactSupport("doc-1", "Employed(Alice)"),+ FactSupport("doc-2", "Employed(Alice)"),+ ]+ )+ original.apply(assertions=[FactSupport("retired", "Q(a)")])+ original.apply(retractions=["retired"])+ payload = original.to_checkpoint()++ def snapshot(session):+ value = session.snapshot()+ return {+ "version": value.version,+ "facts": sorted(value.facts),+ "active_supports": [asdict(support) for support in value.active_supports],+ }++ def explanations(session):+ return {+ fact: asdict(session.explain(fact))+ for fact in ("Employed(Alice)", "Eligible(Alice)", "Q(a)")+ }++ def delta(value):+ return {+ "version": value.version,+ "added_facts": sorted(value.added_facts),+ "removed_facts": sorted(value.removed_facts),+ "added_supports": [asdict(support) for support in value.added_supports],+ "removed_supports": [asdict(support) for support in value.removed_supports],+ }++ def rejected(session, support_id, fact):+ before = snapshot(session)+ with pytest.raises(ValidationError):+ session.apply(assertions=[FactSupport(support_id, fact)])+ return {+ "error": "ValidationError",+ "before": before,+ "after": snapshot(session),+ "explanations": explanations(session),+ }++ def expected_output():+ steps = [{"reject-rebind": rejected(original, "retired", "Q(b)")}]+ value = original.apply(assertions=[FactSupport("retired", "Q(a)")])+ steps.append(+ {+ "reactivate": {+ "delta": delta(value),+ "state": snapshot(original),+ "explanations": explanations(original),+ }+ }+ )+ value = original.apply(retractions=["doc-1"])+ steps.append(+ {+ "withdraw-first": {+ "delta": delta(value),+ "state": snapshot(original),+ "explanations": explanations(original),+ }+ }+ )+ value = original.apply(retractions=["doc-2"])+ steps.append(+ {+ "withdraw-second": {+ "delta": delta(value),+ "state": snapshot(original),+ "explanations": explanations(original),+ }+ }+ )+ steps.append({"reject-arity": rejected(original, "new-id", "Q(a, b)")})+ value = original.apply()+ steps.append(+ {+ "noop": {+ "delta": delta(value),+ "state": snapshot(original),+ "explanations": explanations(original),+ }+ }+ )+ return {+ "module_path": semantica.__file__,+ "hash_seed": "17",+ "initial": {+ "state": snapshot(original),+ "explanations": explanations(original),+ },+ "steps": steps,+ }++ expected = expected_output()+ env = dict(os.environ, PYTHONHASHSEED="17", PYTHONPATH=str(REPO_ROOT))+ result = subprocess.run(+ [sys.executable, "-c", SUBPROCESS_CHILD_CODE],+ input=json.dumps(payload),+ text=True,+ capture_output=True,+ check=True,+ timeout=30,+ cwd=REPO_ROOT,+ env=env,+ )+ child = json.loads(result.stdout)+ assert child == json.loads(json.dumps(expected))diff --git a/tests/reasoning/test_truth_maintenance_differential.py b/tests/reasoning/test_truth_maintenance_differential.pyindex 3a352814..52e9f296 100644--- a/tests/reasoning/test_truth_maintenance_differential.py+++ b/tests/reasoning/test_truth_maintenance_differential.py@@ -24,11 +24,17 @@ Metamorphic checks:"""import itertools+import jsonimport randomimport pytest-from semantica.reasoning import FactSupport, Rule, TruthMaintenanceSession+from semantica.reasoning import (+ FactSupport,+ MaintenanceDelta,+ Rule,+ TruthMaintenanceSession,+)from semantica.utils.exceptions import ValidationErrorCONSTANTS = ("a", "b", "c")@@ -40,6 +46,7 @@ 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 = atomreturn "{}({})".format(predicate, ", ".join(terms))@@ -52,13 +59,16 @@ def parse_session_fact(text):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))+ 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.@@ -68,7 +78,12 @@ def groundings(rule, facts):"""_rule_id, body_atoms, head_atom = rulevariables = sorted(- {term for atom in body_atoms + (head_atom,) for term in atom[1] if term.startswith("?")}+ {+ term+ for atom in body_atoms + (head_atom,)+ for term in atom[1]+ if term.startswith("?")+ })domain = set()for fact in facts:@@ -82,7 +97,10 @@ def groundings(rule, facts):premises = []satisfied = Truefor predicate, terms in body_atoms:- grounded = (predicate, tuple(substitution.get(term, term) for term in terms))+ grounded = (+ predicate,+ tuple(substitution.get(term, term) for term in terms),+ )if grounded not in facts:satisfied = Falsebreak@@ -90,7 +108,10 @@ def groundings(rule, facts):if not satisfied:continuehead_predicate, head_terms = head_atom- conclusion = (head_predicate, tuple(substitution.get(term, term) for term in head_terms))+ 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@@ -127,6 +148,7 @@ def all_derivations(rules, facts):# Random workload generation# --------------------------------------------------------------------------+def generate_rules(rng):"""12 acyclic rules: head predicate index strictly greater than body indices."""rules = []@@ -139,7 +161,7 @@ def generate_rules(rng):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_choices = sorted(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)@@ -158,6 +180,7 @@ def generate_batch(rng, catalog, supports, counter):be re-activated, but only with their permanently bound atom."""retractions = rng.sample(sorted(supports), min(len(supports), rng.randint(0, 3)))+ candidate_catalog = dict(catalog)assertions = []retired = sorted(sid for sid in catalog if sid not in supports)for _ in range(rng.randint(0, 3)):@@ -167,7 +190,7 @@ def generate_batch(rng, catalog, supports, counter):else:sid = f"s{next(counter)}"fact = random_ground_atom(rng)- catalog[sid] = fact+ candidate_catalog[sid] = factif any(sid == existing for existing, _fact in assertions):continueassertions.append((sid, fact))@@ -179,7 +202,7 @@ def generate_batch(rng, catalog, supports, counter):while different == catalog[sid]:different = random_ground_atom(rng)invalid = (sid, different)- return assertions, retractions, invalid+ return assertions, retractions, invalid, candidate_catalogdef build_session(rules):@@ -196,7 +219,8 @@ def compare_session(session, rules, supports, seed, stage, events):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"facts mismatch\nseed={seed}\nstage={stage}\n"+ f"rules={[rule_text(r) for r in rules]}\nevents={events}\n"f"session={sorted(session_facts)}\noracle={sorted(closure)}")derivations = all_derivations(rules, closure)@@ -205,17 +229,23 @@ def compare_session(session, rules, supports, seed, stage, events):expected = derivations.get(fact, [])actual = explanation.derivationsassert 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]}"+ f"derivation count mismatch for {atom_text(fact)}\n"+ f"seed={seed}\nstage={stage}\n"+ f"rules={[rule_text(r) for r in rules]}\nevents={events}\n"+ f"expected={expected}\n"+ f"actual={[(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_idassert 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))+ 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}"+ f"explicit support mismatch for {atom_text(fact)}\n"+ f"seed={seed}\nstage={stage}\nevents={events}")@@ -223,6 +253,7 @@ def compare_session(session, rules, supports, seed, stage, events):# Differential loop# --------------------------------------------------------------------------+def run_seed(seed):rng = random.Random(seed)rules = generate_rules(rng)@@ -251,7 +282,9 @@ def run_seed(seed):version = 1for batch_index in range(60):- assertions, retractions, invalid = generate_batch(rng, catalog, supports, counter)+ assertions, retractions, invalid, candidate_catalog = generate_batch(+ rng, catalog, supports, counter+ )batch = (assertions, retractions, invalid)if invalid is not None:before = (session.version, session.facts)@@ -270,7 +303,9 @@ def run_seed(seed):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 = {+ 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()))@@ -286,26 +321,40 @@ def run_seed(seed):stage = f"batch {batch_index}"assert delta.version == version, (- f"version mismatch\nseed={seed}\nstage={stage}\nevents={events}\nbatch={batch}"+ f"version mismatch\nseed={seed}\nstage={stage}\n"+ f"events={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}"+ assert delta.added_facts == frozenset(+ atom_text(fact) for fact in added_facts+ ), (+ f"added facts mismatch\nseed={seed}\nstage={stage}\n"+ f"events={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}"+ assert delta.removed_facts == frozenset(+ atom_text(fact) for fact in removed_facts+ ), (+ f"removed facts mismatch\nseed={seed}\nstage={stage}\n"+ f"events={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}"+ ), (+ f"added supports mismatch\nseed={seed}\nstage={stage}\n"+ f"events={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}"+ ), (+ f"removed supports mismatch\nseed={seed}\nstage={stage}\n"+ f"events={events}\nbatch={batch}"+ )supports = new_supports+ catalog = candidate_catalogclosure = new_closureevents.append((batch, "applied"))compare_session(session, rules, supports, seed, stage, events)@@ -316,10 +365,427 @@ def test_differential_against_oracle(seed):run_seed(seed)+# --------------------------------------------------------------------------+# Periodic checkpoint continuation differential+# --------------------------------------------------------------------------+++def expected_checkpoint(rule_payload, catalog, supports, version):+ return {+ "format_version": 1,+ "session_version": version,+ "rules": rule_payload,+ "support_catalog": [+ {"support_id": support_id, "fact": atom_text(catalog[support_id])}+ for support_id in sorted(catalog)+ ],+ "active_support_ids": sorted(supports),+ }+++def state_signature(session):+ return (+ session.snapshot(),+ session.to_checkpoint(),+ session.version,+ {fact: session.explain(fact) for fact in session.facts},+ )+++def compare_continuation_pair(+ uninterrupted,+ resumed,+ rules,+ catalog,+ supports,+ version,+ seed,+ stage,+ events,+ expected_rule_payload,+ removed_facts=(),+):+ expected_payload = expected_checkpoint(+ expected_rule_payload, catalog, supports, version+ )+ context = (+ f"seed={seed}\nstage={stage}\nrules={[rule_text(rule) for rule in rules]}"+ f"\nevents={events}"+ )+ assert uninterrupted.snapshot() == resumed.snapshot(), context+ assert uninterrupted.to_checkpoint() == resumed.to_checkpoint(), context+ assert uninterrupted.to_checkpoint() == expected_payload, context++ relevant_facts = set(uninterrupted.facts) | set(removed_facts)+ for fact in relevant_facts:+ assert uninterrupted.explain(fact) == resumed.explain(fact), context++ compare_session(uninterrupted, rules, supports, seed, stage, events)+ compare_session(resumed, rules, supports, seed, stage, events)+++def apply_and_compare_continuation(+ uninterrupted,+ resumed,+ rules,+ catalog,+ supports,+ closure,+ version,+ assertions,+ retractions,+ candidate_catalog,+ seed,+ batch_index,+ events,+ expected_rule_payload,+):+ before_facts = frozenset(uninterrupted.facts)+ uninterrupted_delta = uninterrupted.apply(+ assertions=[FactSupport(sid, atom_text(fact)) for sid, fact in assertions],+ retractions=list(retractions),+ )+ resumed_delta = resumed.apply(+ assertions=[FactSupport(sid, atom_text(fact)) for sid, fact in assertions],+ retractions=list(retractions),+ )++ new_supports = {+ support_id: fact+ for support_id, fact in supports.items()+ if support_id 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+ )+ new_version = version + 1 if changed else version+ expected_delta = MaintenanceDelta(+ version=new_version,+ added_facts=frozenset(atom_text(fact) for fact in added_facts),+ removed_facts=frozenset(atom_text(fact) for fact in removed_facts),+ added_supports=tuple(+ FactSupport(sid, atom_text(new_supports[sid])) for sid in added_support_ids+ ),+ removed_supports=tuple(+ FactSupport(sid, atom_text(supports[sid])) for sid in removed_support_ids+ ),+ )+ context = (+ f"seed={seed}\nstage=batch {batch_index}\n"+ f"rules={[rule_text(rule) for rule in rules]}"+ f"\nevents={events}\nbatch={(assertions, retractions)}"+ )+ assert uninterrupted_delta == expected_delta, context+ assert resumed_delta == expected_delta, context++ compare_continuation_pair(+ uninterrupted,+ resumed,+ rules,+ candidate_catalog,+ new_supports,+ new_version,+ seed,+ f"batch {batch_index}",+ events,+ expected_rule_payload,+ removed_facts=before_facts,+ )+ return new_supports, candidate_catalog, new_closure, new_version, removed_facts+++def restore_resumed_session(resumed):+ return TruthMaintenanceSession.from_checkpoint(+ json.loads(json.dumps(resumed.to_checkpoint()))+ )+++def deterministic_continuation_batch(batch_index, catalog, supports, counter):+ if batch_index == 0:+ fact = ("P0", ("a", "b"))+ return {+ "kind": "create-retired",+ "assertions": [("seed-retired", fact)],+ "retractions": [],+ "invalid": None,+ "candidate_catalog": {**catalog, "seed-retired": fact},+ }+ if batch_index == 1:+ return {+ "kind": "withdraw-retired",+ "assertions": [],+ "retractions": ["seed-retired"],+ "invalid": None,+ "candidate_catalog": dict(catalog),+ }+ if batch_index == 2:+ return {+ "kind": "reject-retired-rebind",+ "assertions": [],+ "retractions": [],+ "invalid": ("seed-retired", ("P1", ("a", "b"))),+ "candidate_catalog": dict(catalog),+ }+ if batch_index == 3:+ return {+ "kind": "reactivate-retired",+ "assertions": [("seed-retired", ("P0", ("a", "b")))],+ "retractions": [],+ "invalid": None,+ "candidate_catalog": dict(catalog),+ }+ if batch_index == 7:+ return {+ "kind": "reject-arity-conflict",+ "assertions": [],+ "retractions": [],+ "invalid": ("arity-probe", ("P0", ("a", "b", "c"))),+ "candidate_catalog": dict(catalog),+ }+ if batch_index == 12:+ return {+ "kind": "unknown-retraction",+ "assertions": [],+ "retractions": ["unknown-id"],+ "invalid": None,+ "candidate_catalog": dict(catalog),+ }+ if batch_index == 17:+ source_id = sorted(supports)[0]+ replacement_id = f"replacement-{next(counter)}"+ return {+ "kind": "source-replacement",+ "assertions": [(replacement_id, supports[source_id])],+ "retractions": [source_id],+ "invalid": None,+ "candidate_catalog": {+ **catalog,+ replacement_id: supports[source_id],+ },+ }+ return None+++def run_checkpoint_seed(seed):+ rng = random.Random(seed)+ rules = generate_rules(rng)+ uninterrupted = build_session(rules)+ expected_rule_payload = build_session(rules).to_checkpoint()["rules"]++ supports = {}+ catalog = {}+ counter = itertools.count()+ for _ in range(15):+ support_id = f"s{next(counter)}"+ fact = random_ground_atom(rng)+ catalog[support_id] = fact+ supports[support_id] = fact+ uninterrupted.apply(+ assertions=[+ FactSupport(support_id, atom_text(fact))+ for support_id, fact in supports.items()+ ]+ )++ version = 1+ closure = oracle_closure(rules, set(supports.values()))+ events = [{"stage": "initial", "kind": "checkpoint"}]+ resumed = restore_resumed_session(uninterrupted)+ compare_continuation_pair(+ uninterrupted,+ resumed,+ rules,+ catalog,+ supports,+ version,+ seed,+ "initial",+ events,+ expected_rule_payload,+ )++ for batch_index in range(60):+ deterministic = deterministic_continuation_batch(+ batch_index, catalog, supports, counter+ )+ if deterministic is not None:+ assertions = deterministic["assertions"]+ retractions = deterministic["retractions"]+ invalid = deterministic["invalid"]+ candidate_catalog = deterministic["candidate_catalog"]+ kind = deterministic["kind"]+ else:+ assertions, retractions, invalid, candidate_catalog = generate_batch(+ rng, catalog, supports, counter+ )+ kind = "random"+ batch = (assertions, retractions, invalid)++ if invalid is not None:+ uninterrupted_before = state_signature(uninterrupted)+ resumed_before = state_signature(resumed)+ with pytest.raises(ValidationError):+ uninterrupted.apply(+ assertions=[+ FactSupport(sid, atom_text(fact))+ for sid, fact in assertions + [invalid]+ ],+ retractions=list(retractions),+ )+ with pytest.raises(ValidationError):+ resumed.apply(+ assertions=[+ FactSupport(sid, atom_text(fact))+ for sid, fact in assertions + [invalid]+ ],+ retractions=list(retractions),+ )+ assert state_signature(uninterrupted) == uninterrupted_before+ assert state_signature(resumed) == resumed_before+ events.append(+ {+ "stage": f"batch {batch_index}",+ "kind": kind,+ "result": "rejected",+ "batch": batch,+ }+ )+ resumed = restore_resumed_session(resumed)+ events.append(+ {+ "stage": f"batch {batch_index}",+ "kind": "checkpoint",+ "location": "after rejected batch",+ }+ )+ compare_continuation_pair(+ uninterrupted,+ resumed,+ rules,+ catalog,+ supports,+ version,+ seed,+ f"batch {batch_index} after rejection",+ events,+ expected_rule_payload,+ )++ probe_id = next(+ (+ support_id+ for support_id, _fact in assertions+ if support_id not in catalog+ ),+ None,+ )+ if probe_id is None:+ probe_id = f"s{next(counter)}"+ probe_fact = random_ground_atom(rng)+ while probe_fact == candidate_catalog.get(probe_id):+ probe_fact = random_ground_atom(rng)+ proof_catalog = dict(catalog)+ proof_catalog[probe_id] = probe_fact+ (+ supports,+ catalog,+ closure,+ version,+ _removed,+ ) = apply_and_compare_continuation(+ uninterrupted,+ resumed,+ rules,+ catalog,+ supports,+ closure,+ version,+ [(probe_id, probe_fact)],+ [],+ proof_catalog,+ seed,+ batch_index,+ events,+ expected_rule_payload,+ )+ events.append(+ {+ "stage": f"batch {batch_index}",+ "kind": "rejected-batch-proof",+ "support_id": probe_id,+ }+ )+ else:+ (+ supports,+ catalog,+ closure,+ version,+ _removed,+ ) = apply_and_compare_continuation(+ uninterrupted,+ resumed,+ rules,+ catalog,+ supports,+ closure,+ version,+ assertions,+ retractions,+ candidate_catalog,+ seed,+ batch_index,+ events,+ expected_rule_payload,+ )+ events.append(+ {+ "stage": f"batch {batch_index}",+ "kind": kind,+ "result": "accepted",+ "batch": batch,+ }+ )++ if (batch_index + 1) % 5 == 0:+ resumed = restore_resumed_session(resumed)+ events.append(+ {+ "stage": f"batch {batch_index}",+ "kind": "checkpoint",+ "location": f"after {batch_index + 1} batches",+ }+ )+ compare_continuation_pair(+ uninterrupted,+ resumed,+ rules,+ catalog,+ supports,+ version,+ seed,+ f"batch {batch_index} periodic checkpoint",+ events,+ expected_rule_payload,+ )++[email protected]("seed", range(20))+def test_checkpoint_differential_against_oracle(seed):+ run_checkpoint_seed(seed)++# --------------------------------------------------------------------------# Metamorphic checks# --------------------------------------------------------------------------+def logical_state(session):return (session.facts,@@ -354,16 +820,25 @@ def test_metamorphic_order_independence():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]+ assertions, retractions, _invalid, candidate_catalog = 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 = {+ key: value for key, value in supports.items() if key not in retractions+ }supports.update(assertions)+ catalog = candidate_catalogassert session_a.facts == session_b.factsfor fact in session_a.facts:- assert session_a.explain(fact).derivations == session_b.explain(fact).derivations+ 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@@ -384,4 +859,4 @@ def test_metamorphic_add_then_retract_restores_state():session.apply(retractions=["probe"])after = logical_state(session)- assert before == after\ No newline at end of file+ assert before == after