knowledge: subject guard + boundary matching + answer log (run H fixes)
Run H (his E2E of run G's fixes) answered Q1 'three longest rivers of
Italy' with the WORLD list (Nile/Amazon/Yangtze fanned out, 226 rows).
Three root causes, all deterministic code (one is an LLM-side miss the
code now guards):
1. THE SUBJECT GUARD (new, _list_from_page): proper nouns of the
question ('Italy') must appear in the article title or the tables'
caption/headers — whole token, stem, or word prefix ('Europe' ->
'European', the gentilici pattern). The disjointness guard was vacuous
(first hop, empty evidence) and the fetch order put the world list
first; the guard now refuses it BEFORE the SELECT_TABLE call (zero
budget spent), logged as 'subject guard: ... refusing LIST'. Live
verified: world article refused, Italy article answered 22 members,
top-3 by table order = Po, Adige, Tiber.
2. WORD-BOUNDARY MATCHING (run H's KG pollution): the harvest ingested
227 world rows as 'Outflow' edges because goal term 'flow' matched
'Outflow' by substring; the discharge-list page did the same with 929
rows. _term_hits/_tokens/_col_hits replace every substring goal-term
match (harvest goal_hit + val_i, promote val_i, skim notice filter);
the keyword fallback ('flow'/'discharge' in ANY header) is gone — the
column must carry a goal term. Live: 0 Outflow edges.
3. THE EXPERT ANSWER LOG (his ask): 'OUTPUT EXPERT: Q1 -> ANSWER
value=3 (list of 3 members: Po, Adige, Tiber) quote=... url=...
[knowledge_graph]' — the answer is now IN the log, not deduced from
the fan-out that follows. Every expert output line carries the qid.
Tests: knowledge/tests/guards.py (boundary matching incl. flow !=
Outflow, proper-noun extraction, subject guard both ways, harvest
boundary, the new ANSWER log format). store.py fixture now names its
subject in the title (predates the law). Suite 52/52. Live smoke: the
full run-H regression chain on real Wikipedia.
This commit is contained in:
@@ -0,0 +1,200 @@
|
||||
"""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.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:
|
||||
table_index = "1"
|
||||
column = "River"
|
||||
set_name = "longest rivers of Italy"
|
||||
origin_question = q
|
||||
|
||||
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")
|
||||
Reference in New Issue
Block a user