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:
+94
-22
@@ -33,6 +33,74 @@ from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
|
||||
|
||||
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
|
||||
class KnowledgeConfig:
|
||||
@@ -280,7 +348,7 @@ class KnowledgeExpert:
|
||||
# pointer, not a dump.
|
||||
notice = sheet.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)))
|
||||
if goal_signal or not goal_terms:
|
||||
self._skim_notices.append(notice)
|
||||
@@ -447,6 +515,22 @@ class KnowledgeExpert:
|
||||
|
||||
Returns the list answer dict, or None when no table in this page
|
||||
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(
|
||||
f"{t.idx} | {t.caption or '(no caption)'} | "
|
||||
f"header: {', '.join(t.header[:6]) or '(none)'} | rows: {t.total_rows}"
|
||||
@@ -612,9 +696,11 @@ class KnowledgeExpert:
|
||||
break
|
||||
if t.idx == getattr(page, "_list_table_idx", -1):
|
||||
continue # the table that answered the LIST question
|
||||
goal_hit = any(gt and (gt in (t.caption or "").casefold()
|
||||
or gt in " ".join(t.header).casefold())
|
||||
for gt in goal_terms)
|
||||
# WORD BOUNDARIES (run H: 'flow' matched 'Outflow' by substring
|
||||
# and 227 world rows entered the KG as 'Outflow' edges)
|
||||
goal_hit = any(
|
||||
_term_hits(gt, (t.caption or "") + " " + " ".join(t.header))
|
||||
for gt in goal_terms)
|
||||
qty_signal = bool(find_quantities(
|
||||
resolve_convert(t.caption or "") + " " + " ".join(t.header[:1])))
|
||||
if not goal_hit:
|
||||
@@ -634,17 +720,10 @@ class KnowledgeExpert:
|
||||
# header names the attribute the goal asks for), keyword
|
||||
# fallbacks (flow/discharge/quantity headers) after
|
||||
ent_i = next((i for i, h in enumerate(t.header)
|
||||
if h.casefold() in ("river", "country", "name", "state",
|
||||
"city", "entity", "member")),
|
||||
0)
|
||||
if h.casefold() in _ENTITY_COL), 0)
|
||||
val_i = next((i for i, h in enumerate(t.header)
|
||||
if i != ent_i and h and any(
|
||||
gt in h.casefold() 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)
|
||||
_term_hits(gt, h) for gt in goal_terms)), None)
|
||||
if val_i is None:
|
||||
self._log(f"skim harvest: table {t.idx} of {page.title}: no "
|
||||
f"value column — recorded, not ingested", think=True)
|
||||
@@ -711,16 +790,9 @@ class KnowledgeExpert:
|
||||
continue
|
||||
page, t = got
|
||||
ent_i = next((i for i, h in enumerate(t.header)
|
||||
if h.casefold() in ("river", "country", "name", "state",
|
||||
"city", "entity", "member")),
|
||||
0)
|
||||
if h.casefold() in _ENTITY_COL), 0)
|
||||
val_i = next((i for i, h in enumerate(t.header)
|
||||
if col and col.casefold() in h.casefold()), 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 col and _col_hits(col, h)), None)
|
||||
if val_i is None:
|
||||
continue
|
||||
overlap, nm = self._entity_overlap_count(t, ent_i, expected)
|
||||
|
||||
Reference in New Issue
Block a user