Files
onibot 65d42d1942 knowledge: typed outputs for all 5 remaining signatures (block PR)
The typed-output migration completes: every knowledge signature now
declares its structure as Python types and dspy renders/parses it.

- TranslateSignature: queries/entities as list[str] — the
  'QUERIES:'/'ENTITIES:' line protocol and its prefix-scraping parser
  are gone
- AnswerFromKG: confidence is a local Confidence(str, Enum)
  (knowledge stays decoupled from floop)
- SelectTableSignature: chosen is TableChoice | None (index int,
  column, set_name) — 'NONE' string handling gone; origin_question
  dropped (it duplicated the input)
- SkimPromoteSignature: decisions as list[PromotionDecision]
  (table_index int, promote bool, column) — the 'idx: YES col' regex
  parser gone
- VerifyCountSignature: unchanged shape (quote str + NOQUOTE
  convention predates typed migration; kept — it is an answer-shaped
  field, not a format protocol)

Callers consume typed objects directly. Test fakes updated to the new
contracts (promote/store/guards).

VERIFIED:
- suite 14/14 green (84 tests)
- live E2E (ollama-cloud glm-5.3-flash, Italy rivers, fresh KG):
  correct answer 2014 m3/s (Po 1540 + Adige 235 + Tiber 239) with
  verified join; wire prompts show list[str]/TableChoice/Confidence/
  list[Fact] schemas rendered natively
2026-10-22 15:11:33 +02:00

199 lines
7.5 KiB
Python

"""PR-5 tests: subject guard, word-boundary matching, and the EXPERT answer
log. The run-H failure chain: Q1 (Italy) answered by the WORLD rivers list
because (a) the article title was never checked against the question's
proper nouns, (b) 'flow' matched 'Outflow' by substring and 227 world rows
entered the KG, (c) the expert's answer was only deducible from the fan-out.
No network, no real LLM. Run: uv run python knowledge/tests/guards.py
"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
from knowledge.wiki import WikiPage, parse_tables
from knowledge.extract import TableChoice
from knowledge.expert import (KnowledgeExpert, KnowledgeConfig,
_tokens, _term_hits, _proper_nouns)
from knowledge.store import KnowledgeStore
# --- fixtures ----------------------------------------------------------------
WORLD_WIKITEXT = (
'{| class="wikitable"\n'
"! Rank !! River !! Length (km) !! Outflow\n|-\n"
"| 1 || Nile || 6650 || Mediterranean\n|-\n"
"| 2 || Amazon || 6400 || Atlantic\n|-\n"
"| 3 || Yangtze || 6300 || East China Sea\n|}\n"
)
ITALY_WIKITEXT = (
'{| class="wikitable"\n'
"|+ Rivers of Italy by length\n"
"! River !! Length (km) !! Flow at the mouth\n|-\n"
"| Po || 652 || 1540\n|-\n"
"| Adige || 410 || 235\n|-\n"
"| Tiber || 406 || 239\n|}\n"
)
def world_page() -> WikiPage:
t = parse_tables(WORLD_WIKITEXT)
return WikiPage(title="List of river systems by length", url="http://x",
pageid=1, fetched_at="t", text="World rivers.",
wikitext=WORLD_WIKITEXT, tables=t)
def italy_page() -> WikiPage:
t = parse_tables(ITALY_WIKITEXT)
return WikiPage(title="List of rivers of Italy", url="http://x", pageid=2,
fetched_at="t", text="Italy has rivers.",
wikitext=ITALY_WIKITEXT, tables=t)
def make_expert(store: KnowledgeStore) -> KnowledgeExpert:
e = KnowledgeExpert.__new__(KnowledgeExpert) # no LLM init
e.cfg = KnowledgeConfig()
e.store = store
e.streams = None
e._checked = e._merged = 0
e._seen_pages = {}
e._skim_leads = []
e._skim_notices = []
e._link_queue = []
e._current_goal_terms = []
e._current_goal_question = ""
class _NoQuote:
quote = ""
e.verify_count = lambda **kw: _NoQuote() # no corroboration in tests
return e
# --- 1) boundary matching ----------------------------------------------------
def test_term_hits():
# 'flow' must NOT match 'Outflow' (the run-H substring bug)
assert _term_hits("flow", "Flow at the mouth") is True
assert _term_hits("flow", "Outflow") is False
assert _term_hits("outflow", "Outflow") is True
# stems tolerated
assert _term_hits("flows", "Flow at the mouth") is True
# whole-token, case-insensitive
assert _term_hits("italy", "Rivers of Italy by length") is True
assert _term_hits("italy", "Italian unification") is False # no substring
print("ok: _term_hits word boundaries (flow != Outflow; italy != Italian)")
def test_proper_nouns():
q = "Which are the three longest rivers of Italy?"
assert _proper_nouns(q) == {"Italy"}
q2 = "What is the discharge of the Po, Adige and Tiber?"
assert _proper_nouns(q2) == {"Po", "Adige", "Tiber"}
q3 = "What is the total water flow considering the three longest rivers of Italy?"
assert _proper_nouns(q3) == {"Italy"}
print("ok: _proper_nouns extracts the subject (Italy; Po/Adige/Tiber)")
# --- 2) the subject guard on LIST --------------------------------------------
def test_subject_guard_list():
import tempfile
q = "Which are the three longest rivers of Italy?"
# (a) the WORLD page must be refused BEFORE any LLM call: no 'italy'
# token in title/captions/headers
tmp = tempfile.mkdtemp()
e = make_expert(KnowledgeStore(f"{tmp}/kg.sqlite"))
called = []
e.select_table = lambda **kw: called.append(kw) or None
ans = e._list_from_page(world_page(), q, None)
assert ans is None, "world page must not answer the Italy question"
assert not called, "the SELECT_TABLE call must not even happen (guard first)"
rows = e.store.probe(["nile", "member"])
assert rows == [], "no rows ingested from the refused world page"
# (b) the ITALY page passes the guard and ingests
tmp2 = tempfile.mkdtemp()
e2 = make_expert(KnowledgeStore(f"{tmp2}/kg.sqlite"))
class Pred:
chosen = TableChoice(table_index=1, column="River",
set_name="longest rivers of Italy")
e2.select_table = lambda **kw: Pred()
ans2 = e2._list_from_page(italy_page(), q, None)
assert ans2 is not None and ans2["list_count"] == 3, ans2
assert ans2["list_items"] == ["Po", "Adige", "Tiber"]
print("ok: subject guard refuses world page, accepts Italy page")
# --- 3) the harvest no longer ingests Outflow --------------------------------
def test_harvest_outflow_boundary():
import tempfile
tmp = tempfile.mkdtemp()
store = KnowledgeStore(f"{tmp}/kg.sqlite")
e = make_expert(store)
e._current_goal_terms = ["total", "water", "flow"]
# the WORLD page: header 'Outflow' must NOT match goal term 'flow' ->
# no harvest at all
n = e._harvest_side_tables(world_page(), None, "flow?", "")
assert n == 0, f"Outflow must not harvest: {n}"
assert store.probe(["nile"]) == [] or all(
"Outflow" not in r.rel for r in store.probe(["nile"])), \
"no Outflow edges may exist"
# the ITALY page: 'Flow at the mouth' DOES match -> ingested
e2 = make_expert(KnowledgeStore(f"{tempfile.mkdtemp()}/kg.sqlite"))
e2._current_goal_terms = ["total", "water", "flow"]
n2 = e2._harvest_side_tables(italy_page(), None, "flow?", "")
assert n2 == 1, f"Italy flow table must harvest: {n2}"
# probe by the relation word ('po' is a 2-char seed, filtered by law)
rows = e2.store.probe(["flow"])
assert any(r.rel == "Flow at the mouth" and r.dst == "1540" for r in rows), rows
print("ok: harvest boundary — Outflow not harvested, Flow at the mouth yes")
# --- 4) the EXPERT answer log -------------------------------------------------
def test_expert_answer_log():
from floop.stream import RunStreams
import tempfile
streams = RunStreams("guard test", verbose=False, runs_dir=tempfile.mkdtemp())
from floop.engine import KnowledgeEngine
class KE:
def answer_question(self, question, parent_question=None, evidence="",
charge_llm=None, answer_type=None):
return {"value": "3", "source": "knowledge_graph",
"list_items": ["Po", "Adige", "Tiber"], "list_count": 3,
"quote": "Po | 652 | 1540", "url": "http://x",
"confidence": "high", "stats": {}}
ke = KnowledgeEngine(KE())
ke.charge = lambda: None
class Table:
def rows(self):
return []
ke.run("Q1", "Which are the three longest rivers of Italy?", None,
Table(), "LIST", streams=streams)
log = (streams.run_dir / "run.log").read_text()
assert "Q1 -> ANSWER value=3" in log, log
assert "list of 3 members: Po, Adige, Tiber" in log, log
assert "quote=Po | 652 | 1540" in log, log
assert "url=http://x" in log, log
print("ok: EXPERT answer log shows the full answer (Q1 -> ANSWER ...)")
if __name__ == "__main__":
test_term_hits()
test_proper_nouns()
test_subject_guard_list()
test_harvest_outflow_boundary()
test_expert_answer_log()
print("\nguards tests passed")