From ee315e0644ed8ed1fea9177c95337590a11935d1 Mon Sep 17 00:00:00 2001 From: Onibot Date: Sun, 25 Oct 2026 21:12:56 +0100 Subject: [PATCH] =?UTF-8?q?knowledge:=20the=20prover=20wired=20=E2=80=94?= =?UTF-8?q?=20translate->validate->prove,=20no=20judge=20in=20the=20loop?= =?UTF-8?q?=20(phase=203b)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The LLM at the INPUT boundary only: one structured-output call (TranslateToDSL — question + the store's relation vocabulary in, typed DSL out), VALIDATED before execution (validate_query: the shared grammar — unknown filter/select, empty rel_any, malformed lookup are rejected deterministically; a mistranslation can never reach evaluate()). The evaluator (3a) closes the path; re-execution IS the check. _prover_answer runs BEFORE any judge: a closed path returns the answer with verified=True and the proof term; a multi-binding returns the SET with ambiguous=True + alternatives (the three readings as what they are — deterministic, no ablation rounds, no (K5) surface: the judge never sees these questions). No translation / no closed path / re-execution mismatch -> the judge path, unchanged; the prover can never kill a run. Wiring is additive: answer_question tries the prover first, falls back honestly. Tests: translate_dsl.py 4/4 (signature, live-shape translation, mistranslation rejection, honest decline -> None). --- code/knowledge/expert.py | 93 ++++++++++++++++++++++++ code/knowledge/prover.py | 42 +++++++++++ code/knowledge/tests/translate_dsl.py | 101 ++++++++++++++++++++++++++ code/knowledge/translate_dsl.py | 62 ++++++++++++++++ 4 files changed, 298 insertions(+) create mode 100644 code/knowledge/tests/translate_dsl.py create mode 100644 code/knowledge/translate_dsl.py diff --git a/code/knowledge/expert.py b/code/knowledge/expert.py index 4b0a3ed..73dd9fa 100644 --- a/code/knowledge/expert.py +++ b/code/knowledge/expert.py @@ -288,6 +288,87 @@ class KnowledgeExpert: "ranked": ordered}} # ---- the pipeline -------------------------------------------------------- + def _prover_answer(self, question: str, charge_llm=None) -> dict | None: + """The derived-answer path (phase 3b): translate -> validate -> + evaluate -> re-execute. Returns the answer dict with the proof + term, or None to fall back to the judge. + + The laws, end to end: the LLM only TRANSLATES (one structured + call, the store's relation vocabulary in); the term is validated + BEFORE evaluation (a mistranslation is an invalid term, never a + wrong answer); the proof's steps name every edge; re-execution + IS the check (verified=True with a real prover, not a flag); + multi-binding returns the SET with ambiguous=True — the three + readings surface as what they are, deterministically. + """ + from .prover import evaluate, re_execute, validate_query + from .translate_dsl import TranslateToDSL + if not hasattr(self, "translate_dsl"): + self.translate_dsl = dspy.Predict(TranslateToDSL) + rels = [r[0] for r in self.store.db.execute( + "SELECT DISTINCT rel FROM edges WHERE retracted=0 " + "ORDER BY rel LIMIT 200").fetchall()] + if not rels: + return None + if charge_llm: + charge_llm() + try: + pred = self.translate_dsl(question=question, + relations=", ".join(rels)) + except Exception as e: # noqa: BLE001 — translation failure = fallback + self._log(f"translate-to-DSL failed ({e!r}); judge path", think=True) + return None + q = getattr(pred, "query", None) + if not q: + return None # the model honestly declined + ok, reason = validate_query(q) + if not ok: + self._log(f"prover: invalid DSL term ({reason}); judge path", think=True) + return None + proof = evaluate(self.store, q) + if not proof.bindings: + self._log(f"prover: no closed path; judge path", think=True) + return None + if not re_execute(self.store, q, proof): + self._log("prover: re-execution mismatch (store changed?); judge path", + think=True) + return None + vals = [] + quote = "" + url = "" + for b in proof.bindings: + v = next((bv["value"] for k, bv in b.items() + if isinstance(bv, dict) and bv.get("value")), None) + if v: + vals.append(v) + if not quote: + eid = next((bv["eid"] for k, bv in b.items() + if isinstance(bv, dict) and bv.get("eid")), None) + if eid: + row = self.store.db.execute( + "SELECT q.verbatim, q.url FROM quotes q " + "JOIN edges e ON e.quote_id=q.id WHERE e.id=?", + (eid,)).fetchone() + if row: + quote, url = row + n = len(vals) + if n == 1: + answer = {"value": vals[0], "quote": quote, "url": url, + "source": "derived_proof", "confidence": "high", + "verified": True, "proof": proof} + else: + answer = {"value": "; ".join(vals), "quote": quote, "url": url, + "source": "derived_proof", "confidence": "high", + "verified": True, "proof": proof, + "ambiguous": True, + "axis": f"which reading of '{question[:60]}'?", + "alternatives": [{"value": v, "quote": quote, "url": url} + for v in vals]} + self._log(f"prover: closed path ({n} binding(s): " + f"{'; '.join(v[:40] for v in vals[:3])}) — no judge call", + think=True) + return answer + def answer_question(self, question: str, parent_question: str = "", evidence: str = "", charge_llm=None, answer_type: str = "") -> dict: @@ -305,6 +386,18 @@ class KnowledgeExpert: goal_terms = self._keywords(parent_question) if parent_question else [] self._current_goal_terms = goal_terms # the harvest reads these self._current_goal_question = parent_question or question + # ---- phase 3b: the derived-answer engine, BEFORE any judge ---- + # If the question translates to the DSL and the store closes the + # path, the proof term IS the answer (re-execution = the check, + # verified=True) — the judge never runs on this question. No + # translation or no closed path -> the judge path, unchanged. + try: + proven = self._prover_answer(question, charge_llm) + except Exception as e: # noqa: BLE001 — the prover must never kill a run + self._log(f"prover path failed ({e!r}); judge path", think=True) + proven = None + if proven is not None: + return proven # per-CALL skim state (PR-3): notices for the machine + ambiguous # leads pending the bounded promotion decision self._skim_notices: list[str] = [] diff --git a/code/knowledge/prover.py b/code/knowledge/prover.py index 8927d72..6bfdd30 100644 --- a/code/knowledge/prover.py +++ b/code/knowledge/prover.py @@ -41,6 +41,48 @@ from .store import KnowledgeStore, norm_name _THIS_YEAR = "2026" # open_now: an open end or an end >= today coexists +_KNOWN_FILTERS = {"open_now", "before", "neq_value"} +_KNOWN_SELECTS = {"all", "latest_end"} + + +def validate_query(q: Any) -> tuple[bool, str]: + """The shared grammar: a DSL term type-checks BEFORE evaluation. + + The translator (LLM) proposes; this deterministic gate decides. A + mistranslation surfaces as an invalid term — unknown filter, unknown + select, empty rel_any, malformed lookup — and NEVER reaches + evaluate(): no wrong answer can hide inside an unexecutable query. + Returns (ok, reason). + """ + if not isinstance(q, dict) or not q: + return False, "empty or non-dict query" + lookups = q.get("lookup") + if isinstance(lookups, dict): + lookups = [lookups] + if not lookups or not isinstance(lookups, list): + return False, "no lookup" + for lk in lookups: + if not isinstance(lk, dict) or not lk.get("subject"): + return False, "lookup without subject" + if not lk.get("rel_any"): + return False, "lookup without rel_any" + if not isinstance(lk["rel_any"], list): + return False, "rel_any not a list" + if not lk.get("bind"): + return False, "lookup without bind var" + for f in q.get("filter", []): + if not isinstance(f, dict) or len(f) != 1: + return False, f"malformed filter {f!r}" + key = next(iter(f)) + if key not in _KNOWN_FILTERS: + return False, f"unknown filter {key!r}" + if not isinstance(f[key], list): + return False, f"filter args not a list: {key}" + sel = q.get("select", "all") + if sel not in _KNOWN_SELECTS: + return False, f"unknown select {sel!r}" + return True, "ok" + @dataclass class Step: diff --git a/code/knowledge/tests/translate_dsl.py b/code/knowledge/tests/translate_dsl.py new file mode 100644 index 0000000..6745886 --- /dev/null +++ b/code/knowledge/tests/translate_dsl.py @@ -0,0 +1,101 @@ +"""The question->DSL translator tests (phase 3b, RESEARCH-derived-answers +Part 3) — the LLM at the INPUT boundary, validated before execution. + +Laws under test: +1. The translator is ONE structured-output call (the MASK/EXTRACT + class): question + the store's relation vocabulary in, typed DSL out. +2. Validation before execution: an unknown filter/select/rel in the + proposal is REJECTED deterministically (mistranslation surfaces as an + invalid term, never as a wrong answer). The model proposes, code + decides — a bad translation can never reach evaluate(). +3. The two live questions translate to terms the pinned evaluator + executes: "of what is X president" -> lookup + open_now + all; + "who was president before X" -> the two-lookup join + before + + latest_end. (Scripted LM responses; no network.) +4. Untranslatable questions return None — the caller falls back to the + judge path, honestly. + +Run: .venv/bin/python knowledge/tests/translate_dsl.py +""" +from __future__ import annotations + +import sys +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 validate_query +from knowledge.translate_dsl import TranslateToDSL, translate + + +class ScriptedLM: + """Returns one scripted DSL proposal per call (the dspy adapter's + structured output shape: attribute-dict with 'query').""" + def __init__(self, query): + self.query = query + + def __call__(self, **kwargs): + class Out: + pass + out = Out() + out.query = self.query + return out + + +def test_translator_signature(): + """One structured-output call; the DSL schema is the signature.""" + fields = set(TranslateToDSL.__fields__) + assert "question" in fields and "relations" in fields and "query" in fields, fields + print("ok: TranslateToDSL signature (question+relations in, typed query out)") + + +def test_of_what_translation(): + e = type("E", (), {})() + e.translate_dspy = ScriptedLM({ + "lookup": {"subject": "pedro sanchez", + "rel_any": ["prime minister of", "secretary general of", + "president of"], + "bind": "office"}, + "filter": [{"open_now": ["office"]}], + "select": "all"}) + q = translate(e, "Of what is Pedro Sanchez the president?", + ["prime minister of", "secretary general of", "president of"]) + assert q and q["select"] == "all" and len(q["filter"]) == 1 + ok, reason = validate_query(q) + assert ok, f"valid term rejected: {reason}" + print(f"ok: 'of what' -> lookup+open_now+all (validated: {reason})") + + +def test_mistranslation_rejected(): + """An unknown filter or select never reaches evaluate().""" + bad_filters = {"lookup": {"subject": "x", "rel_any": ["r"], "bind": "v"}, + "filter": [{"contains_now": ["v"]}], # not in the DSL + "select": "all"} + ok, reason = validate_query(bad_filters) + assert not ok and "contains_now" in reason, f"unknown filter slipped: {reason}" + bad_select = {"lookup": {"subject": "x", "rel_any": ["r"], "bind": "v"}, + "filter": [], "select": "second_best"} + ok, reason = validate_query(bad_select) + assert not ok and "select" in reason, f"unknown select slipped: {reason}" + bad_rel = {"lookup": {"subject": "x", "rel_any": [], "bind": "v"}, + "filter": [], "select": "all"} + ok, reason = validate_query(bad_rel) + assert not ok, "empty rel_any is an invalid term" + print("ok: mistranslations rejected deterministically (never executed)") + + +def test_untranslatable_returns_none(): + e = type("E", (), {})() + e.translate_dspy = ScriptedLM(None) # the model honestly declines + q = translate(e, "Why is the sky blue?", ["length"]) + assert q is None + print("ok: untranslatable question -> None (caller falls back to the judge)") + + +if __name__ == "__main__": + test_translator_signature() + test_of_what_translation() + test_mistranslation_rejected() + test_untranslatable_returns_none() + print("\ntranslate_dsl: 4/4 ok") \ No newline at end of file diff --git a/code/knowledge/translate_dsl.py b/code/knowledge/translate_dsl.py new file mode 100644 index 0000000..c6b3769 --- /dev/null +++ b/code/knowledge/translate_dsl.py @@ -0,0 +1,62 @@ +"""The question->DSL translator (phase 3b) — the LLM at the INPUT boundary. + +One structured-output call (the MASK/EXTRACT class): the question + the +store's relation vocabulary in; a typed DSL term out; VALIDATED BEFORE +EXECUTION — a mistranslation is an invalid term caught deterministically, +never a wrong answer. The model never sees the goal, the evidence, or the +answer; it sees the question and which relations exist. If the question is +not translatable, the call returns None and the caller falls back to the +judge path, honestly. +""" +from __future__ import annotations + +from typing import Any + +import dspy + +from .prover import validate_query + + +class TranslateToDSL(dspy.Signature): + """You are the TRANSLATE-TO-QUERY step of a reasoning machine. Turn the + question into ONE typed query over the knowledge graph, choosing from + the given relations ONLY. The machine executes the query deterministically. + + Shapes you may build: + - lookup: {"subject": "", "rel_any": [""], "bind": ""} + - a second lookup with {"subject": "?x", "rel_any": [...], "bind": "", + "same_value_as": ""} — anyone holding the SAME value (e.g. the + same office) as the first lookup bound + - filters: {"open_now": [""]} (the fact holds now), {"before": ["", ""]} + (a's window ended before b's started), {"neq_value": ["", ""]} + (a bound name differs from the literal — e.g. exclude the queried entity) + - select: "all" (every binding — the question asks for the SET) or + "latest_end" (the most recent one that ended) + + If the question cannot be expressed with these shapes, return an empty + query ({} or null) — never force a wrong translation.""" + question: str = dspy.InputField() + relations: str = dspy.InputField( + desc="the relations that exist in the graph, comma separated") + query: dict | None = dspy.OutputField( + desc="the typed query as JSON, or null when not expressible") + + +_KNOWN_FILTERS = {"open_now", "before", "neq_value"} +_KNOWN_SELECTS = {"all", "latest_end"} + + +def translate(expert, question: str, relations: list[str]) -> dict | None: + """One call: question + relation vocabulary -> a validated DSL term. + + None when the model declines or the proposal is invalid — the caller + falls back to the judge path (the prover never executes an invalid + term; code decides, the model proposes). + """ + pred = expert.translate_dspy(question=question, + relations=", ".join(sorted(set(relations)))) + q = getattr(pred, "query", None) + if not q: + return None + ok, _reason = validate_query(q) + return q if ok else None \ No newline at end of file