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).
101 lines
4.1 KiB
Python
101 lines
4.1 KiB
Python
"""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") |