knowledge: subject guard + boundary matching + answer log (run H) #5

Merged
onibot merged 1 commits from feature/subject-guard into main 2026-10-21 09:43:04 +02:00
4 changed files with 307 additions and 28 deletions
Showing only changes of commit 0ef4f32c8f - Show all commits
+12 -5
View File
@@ -162,16 +162,23 @@ class KnowledgeEngine:
prov["parent_question"] = parent_question prov["parent_question"] = parent_question
note = "" if value.upper() != "UNKNOWN" else "knowledge returned UNKNOWN" note = "" if value.upper() != "UNKNOWN" else "knowledge returned UNKNOWN"
if streams is not None: if streams is not None:
# LIST rows: value is the COUNT — the members are the real answer; # THE ANSWER, in full view (run H: the first knowledge answer was
# render them (first 10, then +N) or the log shows an opaque '22' # only deducible from the fan-out that followed). Q ref + every
# field the machine will act on.
qref = qid if qid else "Q?"
if isinstance(ans.get("list_items"), list) and ans["list_items"]: if isinstance(ans.get("list_items"), list) and ans["list_items"]:
items = ans["list_items"] items = ans["list_items"]
shown = ", ".join(items[:10]) + (f" (+{len(items) - 10} more)" if len(items) > 10 else "") shown = ", ".join(items[:8]) + (f" (+{len(items) - 8} more)" if len(items) > 8 else "")
streams.output("EXPERT", streams.output("EXPERT",
f"value={value} list={shown} [{src}]") f"{qref} -> ANSWER value={value} (list of "
f"{len(items)} members: {shown}) quote="
f"{(ans.get('quote') or '')[:60]} url="
f"{ans.get('url') or ''} [{src}]")
else: else:
streams.output("EXPERT", streams.output("EXPERT",
f"value={value} quote={(ans.get('quote') or '')[:80]} [{src}]") f"{qref} -> ANSWER value={value} quote="
f"{(ans.get('quote') or '')[:80]} url="
f"{ans.get('url') or ''} [{src}]")
return EvidenceRow( return EvidenceRow(
qid=qid, qid=qid,
answer_type=answer_type, answer_type=answer_type,
+94 -22
View File
@@ -33,6 +33,74 @@ from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+") WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
# header/caption terms that name the ENTITY column of a typical scalar table
_ENTITY_COL = ("river", "country", "name", "state", "city", "entity", "member")
def _tokens(text: str) -> set[str]:
"""Casefolded word tokens — the boundary-correct matching base. 'flow'
must not match 'Outflow' (run H: 227 world rows ingested as 'Outflow'
edges because a goal term hit a substring)."""
return {w.casefold() for w in WORD_RE.findall(text or "")}
def _term_hits(term: str, text: str) -> bool:
"""Goal-term match with word boundaries: the term must appear as a
WHOLE token (stem tolerated) in the text's tokens."""
if not term:
return False
toks = _tokens(text)
if term.casefold() in toks:
return True
from .store import stem
return stem(term) in {stem(t) for t in toks if t}
def _col_hits(col: str, header: str) -> bool:
"""The LLM names a column (possibly multi-word: 'Mean discharge').
It matches a header when any of its content tokens appears as a whole
token in the header ('discharge' in 'Average discharge' -> True;
'Flow at the mouth' vs 'Length (km)' -> False)."""
if not col:
return False
stops = {"the", "at", "of", "in", "a", "an", "and"}
from .store import stem
ctoks = {t for t in _tokens(col) if t not in stops and len(t) > 2}
if not ctoks:
return False
htoks = _tokens(header)
hstems = {stem(t) for t in htoks if t}
return any(c in htoks or stem(c) in hstems for c in ctoks)
def _prop_hit(prop: str, toks: set[str]) -> bool:
"""Proper-noun subject match: whole token, stem, or WORD PREFIX —
'Europe' matches 'European' (the gentilici pattern is everywhere on
Wikipedia: 'List of European states' answers 'countries in Europe?').
Prefix >= 4 chars keeps it from matching junk."""
pl = prop.casefold()
from .store import stem
ps = stem(pl)
for t in toks:
if t == pl or stem(t) == ps:
return True
if len(pl) >= 4 and (t.startswith(pl) or pl.startswith(t) and len(t) >= 4):
return True
return False
def _proper_nouns(question: str) -> set[str]:
"""Capitalized non-question words: 'Italy', 'Po' — the SUBJECT of the
question. The definitive guard for 'which are the three longest rivers
of Italy?' never accepting a world table (run H: Q1 answered Nile/
Amazon/Yangtze because the top search hit was the world list and the
disjointness guard was vacuous — no evidence, nothing to check)."""
words = re.findall(r"[A-Z][a-zÀ-ÿ]+(?:'[A-Za-z]+)?", question or "")
stops = {"What", "Which", "Who", "When", "Where", "Why", "How", "The",
"Is", "Are", "Was", "Were", "In", "On", "At", "For", "Of",
"Their", "Its", "Those", "These", "That", "This"}
return {w for w in words if w not in stops}
@dataclass @dataclass
class KnowledgeConfig: class KnowledgeConfig:
@@ -280,7 +348,7 @@ class KnowledgeExpert:
# pointer, not a dump. # pointer, not a dump.
notice = sheet.notice() notice = sheet.notice()
if notice: if notice:
goal_signal = (any(gt in notice.casefold() for gt in goal_terms) goal_signal = (any(_term_hits(gt, notice) for gt in goal_terms)
or any(find_quantities(notice))) or any(find_quantities(notice)))
if goal_signal or not goal_terms: if goal_signal or not goal_terms:
self._skim_notices.append(notice) self._skim_notices.append(notice)
@@ -447,6 +515,22 @@ class KnowledgeExpert:
Returns the list answer dict, or None when no table in this page Returns the list answer dict, or None when no table in this page
enumerates the answer (fall through to the extract path).""" enumerates the answer (fall through to the extract path)."""
# SUBJECT GUARD (run H): proper nouns of the question ('Italy') must
# appear in the article title OR the tables' captions/headers — a
# world list must never answer a question about one country. With no
# evidence yet (first hop), the disjointness guard is vacuous; THIS
# is the guard that fired instead of it.
props = _proper_nouns(question)
if props:
surface = " ".join([page.title]
+ [t.caption or "" for t in page.tables]
+ [" ".join(t.header) for t in page.tables])
toks = _tokens(surface)
if not any(_prop_hit(p, toks) for p in props):
self._log(f"subject guard: {page.title} names none of "
f"{sorted(props)} — refusing LIST from this article",
think=True)
return None
rendered = chr(10).join( rendered = chr(10).join(
f"{t.idx} | {t.caption or '(no caption)'} | " f"{t.idx} | {t.caption or '(no caption)'} | "
f"header: {', '.join(t.header[:6]) or '(none)'} | rows: {t.total_rows}" f"header: {', '.join(t.header[:6]) or '(none)'} | rows: {t.total_rows}"
@@ -612,9 +696,11 @@ class KnowledgeExpert:
break break
if t.idx == getattr(page, "_list_table_idx", -1): if t.idx == getattr(page, "_list_table_idx", -1):
continue # the table that answered the LIST question continue # the table that answered the LIST question
goal_hit = any(gt and (gt in (t.caption or "").casefold() # WORD BOUNDARIES (run H: 'flow' matched 'Outflow' by substring
or gt in " ".join(t.header).casefold()) # and 227 world rows entered the KG as 'Outflow' edges)
for gt in goal_terms) goal_hit = any(
_term_hits(gt, (t.caption or "") + " " + " ".join(t.header))
for gt in goal_terms)
qty_signal = bool(find_quantities( qty_signal = bool(find_quantities(
resolve_convert(t.caption or "") + " " + " ".join(t.header[:1]))) resolve_convert(t.caption or "") + " " + " ".join(t.header[:1])))
if not goal_hit: if not goal_hit:
@@ -634,17 +720,10 @@ class KnowledgeExpert:
# header names the attribute the goal asks for), keyword # header names the attribute the goal asks for), keyword
# fallbacks (flow/discharge/quantity headers) after # fallbacks (flow/discharge/quantity headers) after
ent_i = next((i for i, h in enumerate(t.header) ent_i = next((i for i, h in enumerate(t.header)
if h.casefold() in ("river", "country", "name", "state", if h.casefold() in _ENTITY_COL), 0)
"city", "entity", "member")),
0)
val_i = next((i for i, h in enumerate(t.header) val_i = next((i for i, h in enumerate(t.header)
if i != ent_i and h and any( if i != ent_i and h and any(
gt in h.casefold() for gt in goal_terms)), None) _term_hits(gt, h) for gt in goal_terms)), None)
if val_i is None:
val_i = next((i for i, h in enumerate(t.header)
if i != ent_i and (find_quantities(h)
or "flow" in h.casefold()
or "discharge" in h.casefold())), None)
if val_i is None: if val_i is None:
self._log(f"skim harvest: table {t.idx} of {page.title}: no " self._log(f"skim harvest: table {t.idx} of {page.title}: no "
f"value column — recorded, not ingested", think=True) f"value column — recorded, not ingested", think=True)
@@ -711,16 +790,9 @@ class KnowledgeExpert:
continue continue
page, t = got page, t = got
ent_i = next((i for i, h in enumerate(t.header) ent_i = next((i for i, h in enumerate(t.header)
if h.casefold() in ("river", "country", "name", "state", if h.casefold() in _ENTITY_COL), 0)
"city", "entity", "member")),
0)
val_i = next((i for i, h in enumerate(t.header) val_i = next((i for i, h in enumerate(t.header)
if col and col.casefold() in h.casefold()), None) if col and _col_hits(col, h)), None)
if val_i is None:
val_i = next((i for i, h in enumerate(t.header)
if i != ent_i and (find_quantities(h)
or "flow" in h.casefold()
or "discharge" in h.casefold())), None)
if val_i is None: if val_i is None:
continue continue
overlap, nm = self._entity_overlap_count(t, ent_i, expected) overlap, nm = self._entity_overlap_count(t, ent_i, expected)
+200
View File
@@ -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")
+1 -1
View File
@@ -265,7 +265,7 @@ def test_list_ingest_aggregate(tmp="/tmp/floop_kg_list.sqlite"):
ke.verify_count = FakeNoVerifier() ke.verify_count = FakeNoVerifier()
from knowledge.wiki import WikiPage from knowledge.wiki import WikiPage
page = WikiPage(title="List of states", pageid=1, url="u", page = WikiPage(title="List of European states", pageid=1, url="u",
fetched_at="2026-10-18T00:00:00+00:00", text="x", fetched_at="2026-10-18T00:00:00+00:00", text="x",
tables=[WikiTable(idx=1, header=["Country", "Population"], tables=[WikiTable(idx=1, header=["Country", "Population"],
rows=[["Albania", "2.8"], ["Belgium", "11.8"], rows=[["Albania", "2.8"], ["Belgium", "11.8"],