diff --git a/code/knowledge/prover.py b/code/knowledge/prover.py new file mode 100644 index 0000000..8927d72 --- /dev/null +++ b/code/knowledge/prover.py @@ -0,0 +1,182 @@ +"""The derived-answer engine (phase 3a, RESEARCH-derived-answers Part 3). + +No LLM in the loop. The query is a small TYPED DSL (conjunctive + +temporal, hand-writable — the LLM translator arrives in 3b); the +evaluation is goal-directed over the store; THE ANSWER IS THE PROOF +TERM: every step names its operator and the edge ids it consumed, and +re-execution over the store IS the verification (deterministic, no +model). This is the Logic-LM move of the lineage applied to floop's +own layer: LLMs translate at the two ends, fixed code decides inside. + +DSL (the subset pinned by tests/prover.py): + + {"lookup": {subject, rel_any, bind} | [lookups...] + "filter": [{open_now: [var]}, {before: [a, b]}, {neq_value: [var, lit]}] + "select": "all" | "latest_end"} + +lookup binds `var` to every matching edge (subject exact-normalized, +rel in rel_any). A second lookup may carry same_value_as: var — a join +on the bound value (the SAME office, a different holder). Filters: +open_now (the edge's window is open now — end None or >= today's +year), before (window a ends before window b starts — the interval +succession law), neq_value (a bound subject differs from a literal — +exclusion of the queried entity itself). select: all (the binding SET +— multi-binding IS the ambiguity) or latest_end (the most recent +closed window among the surviving bindings — the predecessor). + +Evaluation semantics, honestly narrow: +- values compare through norm_name (the store's normalization); +- `before` requires BOTH windows to have real endpoints on the + compared sides — an open end is NOT "before" anything (the world + moved on, we cannot prove when); +- select=latest_end sorts by t_end descending, requiring a real t_end; +- nothing is ever invented: no closed path -> empty bindings (UNKNOWN). +""" +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + +from .store import KnowledgeStore, norm_name + +_THIS_YEAR = "2026" # open_now: an open end or an end >= today coexists + + +@dataclass +class Step: + op: str # lookup | filter | select + note: str = "" + edges: list[int] = field(default_factory=list) + + +@dataclass +class Proof: + bindings: list[dict] = field(default_factory=list) + steps: list[Step] = field(default_factory=list) + + +def _edges_of(store: KnowledgeStore, subject: str, rel_any: list[str]) -> list: + """All live edges of one subject under any of the rels (order: id).""" + rows = store.db.execute( + "SELECT e.id, e.rel, e.dst_value, e.t_start, e.t_end, n.norm_name " + "FROM edges e JOIN nodes n ON n.id=e.src_node " + "WHERE n.norm_name=? AND e.retracted=0 ORDER BY e.id", + (norm_name(subject),)).fetchall() + return [r for r in rows if r[1] in rel_any] + + +def _row_to_binding(var: str, r) -> dict: + return {var: {"eid": r[0], "rel": r[1], "value": r[2], + "start": r[3], "end": r[4], "subject": r[5]}} + + +def _window_open_now(b: dict) -> bool: + end = b["end"] + return end is None or end >= _THIS_YEAR + + +def _before(a: dict, b: dict) -> bool: + """Window a ENDED before window b STARTED. Both sides must be real — + an open end is not 'before' anything (honesty: no invented dates).""" + if a["end"] is None or b["start"] is None: + return False + return a["end"] <= b["start"] # year granularity, closed-open + + +def evaluate(store: KnowledgeStore, query: dict) -> Proof: + """Goal-directed evaluation. Returns the proof term (bindings + steps).""" + proof = Proof() + lookups = query.get("lookup") + if isinstance(lookups, dict): + lookups = [lookups] + # ---- first lookup: bind every matching edge ------------------------- + first = lookups[0] + var = first["bind"] + rows = _edges_of(store, first["subject"], first.get("rel_any", [])) + proof.steps.append(Step("lookup", f"bind {var}: subject={first['subject']} " + f"rels={first.get('rel_any')}", + [r[0] for r in rows])) + bindings = [_row_to_binding(var, r) for r in rows] + # ---- further lookups: JOIN on the bound value ----------------------- + for lk in lookups[1:]: + jvar = lk["bind"] + joined = [] + for b in bindings: + same = b[lk.get("same_value_as", var)]["value"] + # the joining side's subject may be a VARIABLE (?x): iterate + # every live edge under the rels and keep value matches + rows = store.db.execute( + "SELECT e.id, e.rel, e.dst_value, e.t_start, e.t_end, n.norm_name " + "FROM edges e JOIN nodes n ON n.id=e.src_node " + "WHERE e.rel IN (%s) AND e.retracted=0 ORDER BY e.id" + % ",".join("?" * len(lk.get("rel_any", []))), + tuple(lk.get("rel_any", []))).fetchall() + for r in rows: + if norm_name(r[2]) == norm_name(same): + nb = dict(b) + nb[jvar] = {"eid": r[0], "rel": r[1], "value": r[2], + "start": r[3], "end": r[4], "subject": r[5]} + nb["?x"] = r[5] # the OTHER holder + joined.append(nb) + proof.steps.append(Step("lookup", f"join {jvar} on value={same}", + [r[0]])) + bindings = joined + # ---- filters ---------------------------------------------------------- + for f in query.get("filter", []): + for key, args in f.items(): + kept = [] + for b in bindings: + if key == "open_now": + ok = _window_open_now(b[args[0]]) + elif key == "before": + ok = _before(b[args[0]], b[args[1]]) + elif key == "neq_value": + # the arg may be a bound edge var (dict) or a plain + # string var ('?x') holding the joined subject's name + ref = b.get(args[0]) + subj = (ref["subject"] if isinstance(ref, dict) + else ref) or "" + ok = norm_name(subj) != norm_name(args[1]) + else: + raise ValueError(f"unknown filter {key!r}") + if ok: + kept.append(b) + proof.steps.append(Step("filter", f"{key} {args}", + [b[var]["eid"] for b in kept if var in b])) + bindings = kept + # ---- select ----------------------------------------------------------- + sel = query.get("select", "all") + if sel == "latest_end": + def _end_key(b): + e = next((v["end"] for k, v in b.items() + if isinstance(v, dict) and v.get("end")), None) + return e or "" + bindings = sorted(bindings, key=_end_key, reverse=True) + bindings = bindings[:1] + proof.steps.append(Step("select", "latest_end", + [b[var]["eid"] for b in bindings if var in b])) + elif sel != "all": + raise ValueError(f"unknown select {sel!r}") + proof.bindings = bindings + return proof + + +def re_execute(store: KnowledgeStore, query: dict, proof: Proof) -> bool: + """The check: the same store must reproduce the SAME closed path. + + Deterministic, no model — evaluation is pure, so this is equality of + the re-run proof term against the claimed one. A store that changed + under the proof (retractions, new edges winning latest_end) makes + the re-run differ and the claimed proof FAILS: the check is real. + """ + fresh = evaluate(store, query) + if len(fresh.bindings) != len(proof.bindings): + return False + for a, b in zip(fresh.bindings, proof.bindings): + ka = {k: (v["eid"] if isinstance(v, dict) else v) + for k, v in a.items()} + kb = {k: (v["eid"] if isinstance(v, dict) else v) + for k, v in b.items()} + if ka != kb: + return False + return True \ No newline at end of file diff --git a/code/knowledge/tests/prover.py b/code/knowledge/tests/prover.py new file mode 100644 index 0000000..47eb183 --- /dev/null +++ b/code/knowledge/tests/prover.py @@ -0,0 +1,160 @@ +"""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") \ No newline at end of file