research/semantic-kg: semantic probe + conflict taxonomy + temporal layer + derived-answer prover #24

Merged
onibot merged 14 commits from research/semantic-kg into main 2026-10-25 21:40:18 +01:00
4 changed files with 298 additions and 0 deletions
Showing only changes of commit ee315e0644 - Show all commits
+93
View File
@@ -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] = []
+42
View File
@@ -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:
+101
View File
@@ -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")
+62
View File
@@ -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": "<entity>", "rel_any": ["<one or more relations>"], "bind": "<var>"}
- a second lookup with {"subject": "?x", "rel_any": [...], "bind": "<var>",
"same_value_as": "<bound var>"} — anyone holding the SAME value (e.g. the
same office) as the first lookup bound
- filters: {"open_now": ["<var>"]} (the fact holds now), {"before": ["<a>", "<b>"]}
(a's window ended before b's started), {"neq_value": ["<var-or-?x>", "<literal>"]}
(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