The typed-output migration completes: every knowledge signature now declares its structure as Python types and dspy renders/parses it. - TranslateSignature: queries/entities as list[str] — the 'QUERIES:'/'ENTITIES:' line protocol and its prefix-scraping parser are gone - AnswerFromKG: confidence is a local Confidence(str, Enum) (knowledge stays decoupled from floop) - SelectTableSignature: chosen is TableChoice | None (index int, column, set_name) — 'NONE' string handling gone; origin_question dropped (it duplicated the input) - SkimPromoteSignature: decisions as list[PromotionDecision] (table_index int, promote bool, column) — the 'idx: YES col' regex parser gone - VerifyCountSignature: unchanged shape (quote str + NOQUOTE convention predates typed migration; kept — it is an answer-shaped field, not a format protocol) Callers consume typed objects directly. Test fakes updated to the new contracts (promote/store/guards). VERIFIED: - suite 14/14 green (84 tests) - live E2E (ollama-cloud glm-5.3-flash, Italy rivers, fresh KG): correct answer 2014 m3/s (Po 1540 + Adige 235 + Tiber 239) with verified join; wire prompts show list[str]/TableChoice/Confidence/ list[Fact] schemas rendered natively
158 lines
6.2 KiB
Python
158 lines
6.2 KiB
Python
"""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.extract import PromotionDecision
|
|
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 typed decisions."""
|
|
def __init__(self, decisions):
|
|
self.decisions = decisions
|
|
self.calls = 0
|
|
|
|
def __call__(self, **kw):
|
|
self.calls += 1
|
|
obj = type("P", (), {})()
|
|
obj.decisions = self.decisions
|
|
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([PromotionDecision(
|
|
table_index=1, promote=True, column="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([PromotionDecision(
|
|
table_index=1, promote=True, column="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([])
|
|
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") |