knowledge: PR-2 opportunistic harvest + seen-index (KNOWLEDGE §7)
The Italy run re-searched from scratch for Adige/Tiber discharge after Q1
had already fetched the article that contains it. PR-2 makes the skim
harvest what it sees in passing:
- _harvest_side_tables: goal-relevant tables beyond the LIST answer are
ingested as typed scalar edges — zero LLM. Detection is deterministic
and goal-directed: the table's caption/header must carry a GOAL term
(the vocabulary the goal asks for, e.g. 'flow' in 'Flow at the mouth');
the entity column must overlap the entities the parent's evidence names
(a world discharge table is refused for Po/Adige/Tiber); the LIST
answer's own table is skipped. Rows become edges: subject = entity
cell, relation = value-column header, object = value + UNIT (the unit
lives in the caption — quantities carry values AND units), quote = the
verbatim stored row line, containment against the stored table text.
- A quantity table with no goal-vocabulary match is RECORDED as a lead
(logged), never ingested on the unit pattern alone — the bounded LLM
promotion is PR-3's call, by design.
- Seen-index (per run): articles already fetched are reused, zero
re-fetch for later questions in the same run.
- Link queue: goal-region links from skim sheets join the candidate
order (capped 12/article); hops still live in the plan — the law stands.
- config: skim_harvest / skim_harvest_max_tables / skim_link_queue.
Live smoke (cold temp store, real Wikipedia): harvesting the Italy list
article during Q1 ingests the discharge table; the Q5 probe
('average annual water flow discharge adige') and Q6 probe now return
'adige | Flow at the mouth | 235 m3/s' and 'tiber | Flow at the mouth |
239 m3/s' from the KG — the exact data Run G died without.
Tests: 4 new (knowledge/tests/harvest.py), suite 39/39 green.
This commit is contained in:
+151
-7
@@ -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]:
|
||||
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
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user