PR-1 made the skim SEE (surfaces + signals); PR-2 made it HARVEST
deterministically. PR-3 closes the loop (KNOWLEDGE.md §7):
- Skim notices: every knowledge answer's stats carry what the fetched
articles contained beyond the answer (table identities, infobox
quantities, link candidates, goal-filtered). The engine copies them
into payload['skim']; the machine renders them to the ROUTER context
('seen in passing (E1): ...') and to the run notes — later steps know
what exists and where it lives instead of re-searching blind. A notice
is a pointer, never evidence: it answers nothing by itself.
- Bounded lead promotion (Emili's 'deterministic + LLM fallback'):
quantity tables that match NO goal word are queued as leads (PR-2);
now ONE dspy call (SkimPromoteSignature) decides over the tables'
IDENTITY lines (caption/headers/rows/quantities — never the rows),
per fetched page with leads, only when leads exist. The LLM proposes;
fixed code disposes: a promoted table still passes the entity-overlap
check (a world discharge table is refused for Po/Adige/Tiber), the
named column must exist, and ingestion goes through the same
containment-checked _ingest_scalar_table as the deterministic path.
- Refactor: row ingestion extracted to _ingest_scalar_table (shared by
harvest + promotion); _entity_overlap_count shared; skim state
(_skim_notices/_skim_leads/_current_goal_question) reset per call.
- find_quantities: fix plain-digit quantities ('1540 m3/s', '1000 m3/s')
— the thousands-separator-only regex missed them, and caption+header
now join with a space ('m3/sRiver' broke the unit boundary).
Live smoke (real Wikipedia, scripted decision): goal terms without
'flow' queue both Italy tables as leads; the promoted 'Flow at the
mouth' table ingests all 27 rivers (Po 1540, Adige 235, Tiber 239
m3/s) containment-checked; promotion of the length table with a
'Flow' column name is refused (column does not exist).
Tests: 4 new (knowledge/tests/promote.py); suite 43/43 green.
139 lines
6.0 KiB
Python
139 lines
6.0 KiB
Python
"""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
|
|
# PR-3 per-call state — every attribute added to __init__ must be
|
|
# injected into __new__-built fakes (pitfall: mid-test AttributeError)
|
|
e._current_goal_terms = []
|
|
e._current_goal_question = ""
|
|
e._skim_notices = []
|
|
e._skim_leads = []
|
|
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") |