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:
@@ -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")
|
||||
Reference in New Issue
Block a user