knowledge: PR-3 skim notices to the loop + bounded lead promotion
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.
This commit is contained in:
@@ -0,0 +1,155 @@
|
||||
"""PR-3 tests: bounded lead promotion + skim notices to the machine.
|
||||
No network, no real LLM. Run: uv run python knowledge/tests/promote.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
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
|
||||
e._current_goal_terms = []
|
||||
e._current_goal_question = "What is the total water flow of the three longest rivers of Italy?"
|
||||
e._skim_notices = []
|
||||
e._skim_leads = []
|
||||
return e
|
||||
|
||||
|
||||
class FakePromote:
|
||||
"""Scripted skim_promote (dspy module shape): returns fixed decision."""
|
||||
def __init__(self, decision: str):
|
||||
self.decision_text = decision
|
||||
self.calls = 0
|
||||
|
||||
def __call__(self, **kw):
|
||||
self.calls += 1
|
||||
obj = type("P", (), {})()
|
||||
obj.decision = self.decision_text
|
||||
return obj
|
||||
|
||||
|
||||
LEAD_WIKITEXT = (
|
||||
'{| class="wikitable"\n'
|
||||
"|+ Rivers of Italy above {{cvt|50|m3/s}} of average discharge\n"
|
||||
"! Rank !! River !! Average discharge\n|-\n"
|
||||
"| 1 || Po || 1540\n|-\n| 4 || Adige || 235\n|-\n| 3 || Tiber || 239\n|}\n")
|
||||
# caption carries the unit signal (50 m3/s) but NO goal word -> a lead
|
||||
WORLD_WIKITEXT = (
|
||||
'{| class="wikitable"\n'
|
||||
"|+ World rivers above {{cvt|1000|m3/s}}\n"
|
||||
"! River !! Mean discharge\n|-\n"
|
||||
"| Amazon || 209000\n|-\n| Congo || 41200\n|-\n| Yangtze || 30166\n|}\n")
|
||||
|
||||
|
||||
def lead_page() -> WikiPage:
|
||||
return WikiPage(title="Hydrology of Italy", pageid=1, url="u1",
|
||||
text="x", fetched_at="t",
|
||||
tables=parse_tables(LEAD_WIKITEXT))
|
||||
|
||||
|
||||
def world_page() -> WikiPage:
|
||||
return WikiPage(title="List of rivers by discharge", pageid=2, url="u2",
|
||||
text="x", fetched_at="t",
|
||||
tables=parse_tables(WORLD_WIKITEXT))
|
||||
|
||||
|
||||
EVIDENCE = "E1: list of 3 items: Po, Adige, Tiber (answers Q1)"
|
||||
|
||||
|
||||
def test_promotion_ingests_goal_table():
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
store = KnowledgeStore(Path(d) / "kg.sqlite")
|
||||
e = make_expert(store)
|
||||
e._current_goal_terms = ["total", "considering"] # no 'flow' — lead path
|
||||
# harvest queues it as a lead (qty signal, no goal term)
|
||||
n = e._harvest_side_tables(lead_page(), None, "q", EVIDENCE)
|
||||
assert n == 0 and len(e._skim_leads) == 1, "queued as lead, not ingested"
|
||||
# bounded promotion: LLM says YES (column Mean discharge)
|
||||
e.skim_promote = FakePromote("1: YES Mean discharge")
|
||||
charged = []
|
||||
p = e._promote_leads(EVIDENCE, lambda: charged.append(1))
|
||||
assert p == 1, "promoted table ingested"
|
||||
assert e.skim_promote.calls == 1, "exactly one bounded call"
|
||||
rows = store.probe(["discharge"])
|
||||
assert any(r.src == "po" and r.dst == "1540 m3/s" for r in rows), \
|
||||
[(r.src, r.dst) for r in rows]
|
||||
assert e._skim_leads == [], "leads consumed after the call"
|
||||
print("ok test_promotion_ingests_goal_table")
|
||||
|
||||
|
||||
def test_promotion_refuses_world_table():
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
store = KnowledgeStore(Path(d) / "kg.sqlite")
|
||||
e = make_expert(store)
|
||||
e._current_goal_terms = ["total"] # no overlap with caption/header
|
||||
n = e._harvest_side_tables(world_page(), None, "q", EVIDENCE)
|
||||
assert n == 0 and len(e._skim_leads) == 1
|
||||
e.skim_promote = FakePromote("1: YES Mean discharge") # LLM WRONG
|
||||
p = e._promote_leads(EVIDENCE, lambda: None)
|
||||
assert p == 0, "code disposes: zero entity overlap -> refused"
|
||||
assert all(r.src != "amazon" for r in store.probe(["discharge"])), \
|
||||
"a world table must never enter the KG for Po/Adige/Tiber"
|
||||
print("ok test_promotion_refuses_world_table")
|
||||
|
||||
|
||||
def test_no_leads_no_call():
|
||||
e = make_expert(KnowledgeStore(":memory:"))
|
||||
e.skim_promote = FakePromote("1: YES x")
|
||||
charged = []
|
||||
p = e._promote_leads(EVIDENCE, lambda: charged.append(1))
|
||||
assert p == 0 and e.skim_promote.calls == 0 and not charged, \
|
||||
"no leads -> zero LLM calls (bounded by construction)"
|
||||
print("ok test_no_leads_no_call")
|
||||
|
||||
|
||||
def test_notice_reaches_router_context():
|
||||
"""PR-3: a knowledge row's skim notice renders in the machine context and
|
||||
lands in the run notes."""
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
|
||||
from floop.machine import FloopRun
|
||||
from floop.state import AnswerType, Budget, EvidenceRow, OpenQuestion
|
||||
from tests.machine import FakeModules, budget # noqa: I001 (tests layout)
|
||||
|
||||
fm = FakeModules(
|
||||
init_subs=[{"text": "q?", "deps": [], "answer_type": "CONSTANT"}],
|
||||
route_fn=lambda q: "numeric")
|
||||
run = FloopRun("goal?", budget(), modules=fm)
|
||||
row = EvidenceRow(
|
||||
qid="Q1", answer_type=AnswerType.CONSTANT,
|
||||
payload={"value": "22",
|
||||
"skim": ["List of rivers of Italy: table 2: Rivers above 50 m3/s | rows: 27"]},
|
||||
engine="knowledge", trace=[], provenance={},
|
||||
verified=False, note="")
|
||||
q = run.stack.items[0]
|
||||
run._append_checked(row, q)
|
||||
assert any("skim" in n and "50 m3/s" in n for n in run.notes), run.notes
|
||||
# router context: a question depending on Q1 sees the seen-in-passing line
|
||||
q2 = OpenQuestion(text="What is the flow of Adige?", deps=["Q1"])
|
||||
run.stack.items.append(q2)
|
||||
ctx = run._context(q2)
|
||||
assert "seen in passing" in ctx and "table 2" in ctx, ctx
|
||||
print("ok test_notice_reaches_router_context")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_promotion_ingests_goal_table()
|
||||
test_promotion_refuses_world_table()
|
||||
test_no_leads_no_call()
|
||||
test_notice_reaches_router_context()
|
||||
print("\npromote PR-3 tests passed")
|
||||
Reference in New Issue
Block a user