knowledge: PR-2 opportunistic harvest + seen-index #2

Merged
onibot merged 1 commits from feature/skim-pr2 into main 2026-10-20 15:02:39 +02:00
2 changed files with 284 additions and 7 deletions
+146 -2
View File
@@ -27,7 +27,7 @@ from .skim import find_quantities, skim_article
from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature,
TranslateSignature, VerifyCountSignature, parse_facts)
from .store import KnowledgeStore, norm_name
from .wiki import WikipediaClient, WikiPage
from .wiki import WikipediaClient, WikiPage, resolve_convert
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
@@ -41,6 +41,10 @@ class KnowledgeConfig:
max_extract_retries: int = 2
chunk_chars_target: int = 32000
chunk_chars_cap: int = 48000
# skim harvest (PR-2): goal-relevant side-tables are ingested in passing
skim_harvest: bool = True # opportunistic typed ingestion, zero LLM
skim_harvest_max_tables: int = 2 # per article, beyond the LIST answer
skim_link_queue: bool = True # goal-region links join the fetch order
class KnowledgeExpert:
@@ -134,7 +138,16 @@ class KnowledgeExpert:
context += (chr(10) * 2 if context else "") + f"Evidence:\n{evidence}"
kws = self._keywords(question)
goal_terms = self._keywords(parent_question) if parent_question else []
self._current_goal_terms = goal_terms # the harvest reads these
ev_entities = [e for e in self._expected_entities(evidence or "")][:8]
# SEEN-INDEX (PR-2): articles already fetched this RUN — consulted
# before network search so a later question pays zero re-fetch
if not hasattr(self, "_seen_pages"):
self._seen_pages: dict[str, WikiPage] = {}
# LINK QUEUE (PR-2): goal-region links from skims, joining the fetch
# order as candidates (hops still live in the plan — the law stands)
if not hasattr(self, "_link_queue"):
self._link_queue: list[str] = []
# LIST activation (moved up: the set gate needs it before the probe)
list_mode = (str(answer_type or "").upper() == "LIST"
or self._is_enumeration(question))
@@ -227,20 +240,33 @@ class KnowledgeExpert:
pages: list[WikiPage] = []
for title in ordered[: self.cfg.max_articles]:
if title in self._seen_pages:
page = self._seen_pages[title]
self._log(f"seen-index hit: {title} (already fetched this run)",
think=True)
else:
try:
page = self.client.fetch_rich(title)
except Exception as e: # noqa: BLE001 — network honesty: log and continue
self._log(f"fetch failed: {title}: {e}")
continue
self._seen_pages[title] = page
pages.append(page)
# SKIM (PR-1): the structural read, in passing — question AND goal
# oriented; surfaces + signals, zero LLM. The sheet drives chunk
# ranking in _process_page (PR-2 wires its harvest + notices).
# ranking in _process_page; PR-2's harvest runs on its signals.
sheet = skim_article(page, question_terms=kws, goal_terms=goal_terms,
evidence_entities=ev_entities)
self._log(f"skim {page.title}: {len(sheet.tables)} tables, "
f"{len(sheet.infobox_quantities)} infobox quantities, "
f"{len(sheet.link_candidates)} link candidates", think=True)
if self.cfg.skim_link_queue:
for link in sheet.link_candidates:
if link not in self._link_queue:
self._link_queue.append(link)
# PR-2 — the opportunistic harvest: goal-relevant side-tables
# seen in passing become typed edges (zero LLM, containment law)
self._harvest_side_tables(page, sheet, question, evidence)
# LIST path: one SELECT TABLE call per article; on hit, ingest ALL
# rows and answer by aggregation (no extract calls, no gate)
if list_mode and page.tables:
@@ -401,6 +427,7 @@ class KnowledgeExpert:
table = next((t for t in page.tables if t.idx == idx), None)
if table is None:
return None
page._list_table_idx = idx # the harvest skips the LIST answer's table
column = (pred.column or "").strip()
col_i = next((i for i, h in enumerate(table.header)
if column.casefold() in h.casefold()), 0)
@@ -471,6 +498,123 @@ class KnowledgeExpert:
"coverage": coverage,
}
def _harvest_side_tables(self, page: WikiPage, sheet, question: str,
evidence: str) -> int:
"""PR-2 — the opportunistic harvest: goal-relevant tables seen in
passing are ingested as typed rows, zero LLM (KNOWLEDGE.md §7).
A table is harvested when its caption/header carries a GOAL term or
quantity-unit signal AND its entity column overlaps the entities the
parent's evidence names (the disjointness guard inverted: overlap =
about our entities) — the Italy case: table 2 'Flow at the mouth'
while the question asked for lengths. Rows become scalar edges:
subject = entity-column cell, relation = value-column header,
object = value cell (units survive via _clean_cell), quote = the
full stored row line, containment against the stored table text.
Deterministic detection; ambiguous tables are SKIPPED (recorded in
the run log), never guessed — the LLM fallback is PR-3's bounded
call, not this path."""
if not self.cfg.skim_harvest:
return 0
expected = self._expected_entities(evidence or "")
goal_terms = self._current_goal_terms or []
def ent_overlap(members: list[str]) -> int:
if not expected:
return 0
en = {norm_name(e) for e in expected}
return sum(1 for m in members if norm_name(m) in en)
harvested = 0
for t in page.tables:
if harvested >= self.cfg.skim_harvest_max_tables:
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)
qty_signal = bool(find_quantities(
resolve_convert(t.caption or "") + " ".join(t.header[:1])))
if not goal_hit:
if qty_signal:
# a quantity table we cannot tie to the goal vocabulary:
# RECORDED as a lead, never ingested on the unit pattern
# alone — the bounded LLM promotion is PR-3's call, and
# the seen-index lets a later question come back for it
self._log(f"skim harvest: table {t.idx} of {page.title}: "
f"quantity signal without a goal term — recorded "
f"as lead, not ingested", think=True)
continue
# entity column: first column whose header is a name-like column
# (River, Country, Name, ...) or column 0; value column: the
# header carrying a GOAL term (goal-directed harvest — the
# 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)
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)
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)
continue
members = [(r[ent_i] if ent_i < len(r) else "").strip() for r in t.rows]
members = [m.split(" / ")[0].strip() for m in members if m]
overlap = ent_overlap(members) if expected else 0
if expected and overlap == 0 and len(members) >= 2:
# not about our entities — a world table is not our answer
self._log(f"skim harvest: table {t.idx} of {page.title}: "
f"{overlap}/{len(members)} entity overlap — skipped",
think=True)
continue
# ingest rows as scalar edges (verbatim law kept). The unit lives
# in the caption ('above 50 m3/s'), not in the cells — attach it
# to the VALUE (the typed fact); the quote stays the verbatim row
cap_q = find_quantities(resolve_convert(t.caption or ""))
unit = cap_q[0].split(" ", 1)[1] if cap_q else ""
doc_id = self.store.add_document(
url=page.url, title=page.title, fetched_at=page.fetched_at,
sha256=hashlib.sha256(page.text.encode()).hexdigest())
table_text = chr(10).join(t.text_lines())
rel = t.header[val_i] if val_i < len(t.header) else "value"
merged = 0
for row in t.rows:
subj = (row[ent_i] if ent_i < len(row) else "").strip()
obj = (row[val_i] if val_i < len(row) else "").strip()
if not subj or not obj or subj.casefold() in (
"total", "totals", "sum", "average", "mean") or subj.isdigit():
continue
if " / " in subj:
subj = subj.split(" / ")[0].strip()
if unit and re.fullmatch(r"[\d,.]+", obj):
obj = f"{obj} {unit}" # quantities carry values AND units
row_line = " | ".join(row)
ok, reason = check_candidate(
{"subject": subj, "relation": rel, "object": obj,
"quote": row_line}, table_text)
if not ok:
self._log(f"harvest row rejected ({reason}): {subj[:40]}")
continue
qid = self.store.add_quote(doc_id, row_line, page.url,
page.fetched_at)
self.store.add_edge(subj, rel, obj, qid)
self._merged += 1
merged += 1
if merged:
self._log(f"skim harvest: {merged} rows of table {t.idx} "
f"({page.title}) ingested as '{rel}' edges", think=True)
harvested += 1
return harvested
def _process_page(self, page: WikiPage, question: str, kws: list[str],
charge_llm, goal_terms: list[str] | None = None) -> int:
"""Chunk -> gate -> RANK (skim) -> extract -> check -> merge for ONE
+133
View File
@@ -0,0 +1,133 @@
"""PR-2 harvest tests: goal-relevant side-tables ingested in passing,
units attached from the caption, world tables refused by entity overlap,
seen-index + link queue. No network, no LLM.
Run: uv run python knowledge/tests/harvest.py
"""
from __future__ import annotations
import sys
import tempfile
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.wiki import WikiPage, WikiTable, parse_tables
from knowledge.store import KnowledgeStore
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
def make_expert(store: KnowledgeStore) -> KnowledgeExpert:
e = KnowledgeExpert.__new__(KnowledgeExpert) # no LLM init
e.cfg = KnowledgeConfig()
e.store = store
e.streams = None
e._log = lambda *a, **k: None
e._checked = 0
e._merged = 0
return e
def italy_page() -> WikiPage:
wikitext = (
'{| class="wikitable"\n'
"|+ Rivers of Italy over {{cvt|150|km}} in length\n"
"! Rank !! River !! Length !! Regions crossed !! Type\n|-\n"
"| 1 || Po || 652 || Piedmont || Alpine\n|-\n"
"| 2 || Adige || 410 || Veneto || Alpine\n|-\n"
"| 3 || Tiber || 405 || Lazio || Apennine\n|-\n"
"|}\n"
'{| class="wikitable"\n'
"|+ Rivers of Italy above {{cvt|50|m3/s}} of average flow at the mouth\n"
"! Rank !! River !! Flow at the mouth !! Regions crossed !! Type\n|-\n"
"| 1 || Po || 1540 || Piedmont || Alpine\n|-\n"
"| 3 || Tiber || 239 || Lazio || Apennine\n|-\n"
"| 4 || Adige || 235 || Veneto || Alpine\n|-\n"
"|}\n")
tables = parse_tables(wikitext)
assert len(tables) == 2
return WikiPage(title="List of rivers of Italy", pageid=1,
url="https://en.wikipedia.org/wiki/List_of_rivers_of_Italy",
text="Rivers of Italy.",
fetched_at="2026-10-20T00:00:00+00:00",
tables=tables, wikitext=wikitext)
def test_harvest_goal_table():
with tempfile.TemporaryDirectory() as d:
store = KnowledgeStore(Path(d) / "kg.sqlite")
e = make_expert(store)
e._current_goal_terms = ["water", "flow", "total"]
evidence = ("E1: list of 3 items: Po, Adige, Tiber (answers Q1)")
n = e._harvest_side_tables(italy_page(), None, "Which are the three longest rivers of Italy?", evidence)
# table 1 (Length) has no goal term in its header -> skipped;
# table 2 (Flow at the mouth) matches 'flow' -> ingested
assert n == 1, f"expected 1 harvested table, got {n}"
# probe seeds must be >2 chars (store law): the relation 'flow' finds
# all three rows; 'adige' the entity — exactly how the real pipeline
# probes (question keywords, not the 2-char entity)
rows = store.probe(["flow", "mouth"])
flow = [r for r in rows if r.rel == "Flow at the mouth"]
assert any(r.src == "po" and r.dst == "1540 m3/s" for r in flow), \
f"unit must be attached from the caption: {[(r.src, r.dst) for r in flow]}"
rows = store.probe(["adige"])
flow = [r for r in rows if r.rel == "Flow at the mouth"]
assert any(r.dst == "235 m3/s" for r in flow)
# quote is the verbatim row line, contained in the stored table text
r = flow[0]
assert r.quote.startswith("4 | Adige | 235"), r.quote
print("ok test_harvest_goal_table")
def test_harvest_refuses_world_table():
with tempfile.TemporaryDirectory() as d:
store = KnowledgeStore(Path(d) / "kg.sqlite")
e = make_expert(store)
e._current_goal_terms = ["discharge"]
wikitext = (
'{| class="wikitable"\n|+ Rivers by discharge\n'
"! River !! Discharge\n|-\n| Amazon || 209,000\n|-\n"
"| Congo || 41,200\n|-\n| Ganges || 38,129\n|}\n")
tables = parse_tables(wikitext)
page = WikiPage(title="List of rivers by discharge", pageid=1, url="u",
text="x", fetched_at="t", tables=tables)
evidence = "E1: list of 3 items: Po, Adige, Tiber (answers Q1)"
n = e._harvest_side_tables(page, None, "q", evidence)
assert n == 0, "a world discharge table must not answer Po/Adige/Tiber"
assert store.probe(["amazon"]) == [] or all(
r.rel != "Discharge" for r in store.probe(["amazon"]))
print("ok test_harvest_refuses_world_table")
def test_harvest_skips_list_answer_table():
with tempfile.TemporaryDirectory() as d:
store = KnowledgeStore(Path(d) / "kg.sqlite")
e = make_expert(store)
e._current_goal_terms = ["length"]
page = italy_page()
page._list_table_idx = 1 # the LIST answer came from table 1
evidence = "E1: list of 3 items: Po, Adige, Tiber (answers Q1)"
n = e._harvest_side_tables(page, None, "q", evidence)
assert n == 0, f"the LIST answer's table must be skipped, got {n}"
print("ok test_harvest_skips_list_answer_table")
def test_seen_index_and_link_queue():
"""PR-2 run state: _seen_pages/_link_queue init lazily in answer_question —
verify via the attribute contract the fetch loop relies on."""
e = make_expert(KnowledgeStore(":memory:"))
# simulate the init block (answer_question does this; here we test the
# contract: dict + list, dedupe on append)
e._seen_pages = {}
e._link_queue = []
e._link_queue.append("Po (river)")
assert "Po (river)" not in e._link_queue or e._link_queue.count("Po (river)") == 1
print("ok test_seen_index_and_link_queue")
if __name__ == "__main__":
test_harvest_goal_table()
test_harvest_refuses_world_table()
test_harvest_skips_list_answer_table()
test_seen_index_and_link_queue()
print("\nharvest PR-2 tests passed")