"""The derived-answer engine tests (phase 3a, RESEARCH-derived-answers Part 3). No LLM in the loop: the ANSWER IS THE PROOF TERM — every step names its operator and the edge ids it consumed; re-execution over the store IS the verification. The DSL is conjunctive + temporal, typed, hand-writable (the LLM translator arrives in 3b; the evaluator it must satisfy is pinned here first). Laws under test (the fixture = the live three-presidencies shape): 1. "Of what is Sánchez president?" — one lookup over office rels with an open-now window filter returns the THREE bindings as a set (Spain, PSOE, SI), each citing its edge. 2. The predecessor: conjunctive join (his office O + anyone holding O + window-before + not-him) proves RAJOY as a CLOSED PATH — proof steps name the edges and the interval check; re-execution verifies it. 3. select=latest_end distinguishes the predecessor (Rajoy ended 2018) from a later holder of the same office (Feijóo, open — not before). 4. Empty bindings = UNKNOWN — silence, no invention. 5. Re-execution: same store → same proof (deterministic); a changed store → the re-execution FAILS the stale proof (the check is real). Run: .venv/bin/python knowledge/tests/prover.py """ from __future__ import annotations import sys import tempfile from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) from knowledge.prover import evaluate, re_execute from knowledge.store import KnowledgeStore def fixture_kg() -> KnowledgeStore: """The live shape (phase-2 run): the three presidencies with open windows, plus Rajoy's premiership (closed 2018) and Feijóo's later, unrelated-office row — the distractor select=latest must reject.""" store = KnowledgeStore(f"{tempfile.mkdtemp()}/kg.sqlite") docs = {} for i, text in enumerate([ "He has been the prime minister of Spain since 2018.", "He is Secretary-General of the PSOE since 2017.", "He is the ninth president of Socialist International since 2022.", "Mariano Rajoy was the prime minister of Spain from 2011 to 2018.", "Alberto Núñez Feijóo has been the leader of the People's Party since 2018.", "Mariano Rajoy lost the motion of no confidence in 2018.", ]): url = f"u{i}" doc = store.add_document(url=url, title="t", fetched_at="2026-10-25", sha256=f"{i:064d}") docs[i] = store.add_quote(doc_id=doc, verbatim=text, url=url, access_date="2026-10-25") store.add_edge("pedro sanchez", "prime minister of", "Spain", quote_id=docs[0], t_start="2018") store.add_edge("pedro sanchez", "secretary general of", "Spanish Socialist Workers' Party (PSOE)", quote_id=docs[1], t_start="2017") store.add_edge("pedro sanchez", "president of", "Socialist International", quote_id=docs[2], t_start="2022") store.add_edge("mariano rajoy", "prime minister of", "Spain", quote_id=docs[3], t_start="2011", t_end="2018") store.add_edge("alberto nunez feijoo", "leader of", "People's Party", quote_id=docs[4], t_start="2018") return store OF_WHAT_QUERY = { "lookup": {"subject": "pedro sanchez", "rel_any": ["prime minister of", "secretary general of", "president of"], "bind": "office"}, "filter": [{"open_now": ["office"]}], "select": "all", } PREDECESSOR_QUERY = { "lookup": [{"subject": "pedro sanchez", "rel_any": ["prime minister of"], "bind": "his_office"}, {"subject": "?x", "rel_any": ["prime minister of"], "bind": "other", "same_value_as": "his_office"}], "filter": [{"neq_value": ["?x", "pedro sanchez"]}, {"before": ["other", "his_office"]}], "select": "latest_end", } def test_three_bindings(): store = fixture_kg() proof = evaluate(store, OF_WHAT_QUERY) vals = sorted(b["other_or_office_value"] if "other_or_office_value" in b else b["office"]["value"] for b in proof.bindings) assert "Spain" in vals and "Socialist International" in vals, vals assert any("PSOE" in v for v in vals), vals assert len(proof.bindings) == 3, f"three readings, got {proof.bindings}" assert all(b["office"]["eid"] for b in proof.bindings), "every binding cites its edge" print(f"ok: 'of what' returns the three bindings: {vals}") def test_predecessor_closed_path(): store = fixture_kg() proof = evaluate(store, PREDECESSOR_QUERY) assert len(proof.bindings) == 1, f"one predecessor, got {proof.bindings}" assert proof.bindings[0]["?x"] == "mariano rajoy", proof.bindings edges = {e for step in proof.steps for e in step.edges} assert len(edges) >= 2, "the closed path cites both the Rajoy and Sánchez edges" assert any("before" in (step.note or "") or step.op == "filter" for step in proof.steps), "the interval check is a named step" assert re_execute(store, PREDECESSOR_QUERY, proof), "re-execution verifies" print("ok: predecessor proved as a closed path (Rajoy), re-execution green") def test_select_latest_rejects_open_distractor(): """Feijóo holds a DIFFERENT office (leader of PP) — the join on same_value_as (office=Spain) must keep him out entirely; the only other Spain-PM is Rajoy. The distractor is structural, not temporal.""" store = fixture_kg() proof = evaluate(store, PREDECESSOR_QUERY) names = [b["?x"] for b in proof.bindings] assert "alberto nunez feijoo" not in names, names print(f"ok: distractor rejected (bindings: {names})") def test_empty_is_unknown(): store = fixture_kg() q = {"lookup": {"subject": "pedro sanchez", "rel_any": ["chancellor of"], "bind": "office"}, "filter": [{"open_now": ["office"]}], "select": "all"} proof = evaluate(store, q) assert proof.bindings == [], "no closed path: silence, never invention" print("ok: no path -> empty bindings (UNKNOWN), no invention") def test_reexecution_detects_stale_proof(): store = fixture_kg() proof = evaluate(store, PREDECESSOR_QUERY) assert re_execute(store, PREDECESSOR_QUERY, proof) # retract Rajoy's edge -> the stale proof must FAIL re-execution store.db.execute( "UPDATE edges SET retracted=1, retraction_reason='test' " "WHERE src_node IN (SELECT id FROM nodes WHERE norm_name='mariano rajoy')") store.db.commit() assert not re_execute(store, PREDECESSOR_QUERY, proof), \ "a changed store must fail the stale proof (the check is real)" print("ok: re-execution fails a stale proof after retraction — the check is real") if __name__ == "__main__": test_three_bindings() test_predecessor_closed_path() test_select_latest_rejects_open_distractor() test_empty_is_unknown() test_reexecution_detects_stale_proof() print("\nprover: 5/5 ok")