Merge pull request 'knowledge: PR-3 skim notices + bounded lead promotion' (#3) from feature/skim-pr3 into main

This commit was merged in pull request #3.
This commit is contained in:
2026-10-20 16:24:59 +02:00
7 changed files with 391 additions and 74 deletions
+7
View File
@@ -139,6 +139,13 @@ class KnowledgeEngine:
payload["list_count"] = ans.get("list_count", len(ans["list_items"])) payload["list_count"] = ans.get("list_count", len(ans["list_items"]))
if ans.get("coverage"): if ans.get("coverage"):
payload["coverage"] = ans["coverage"] payload["coverage"] = ans["coverage"]
# PR-3 — the skim notice: what the fetched articles contained beyond
# this answer (tables/infobox/link surfaces with goal signals). A
# POINTER for later steps, not evidence: it never answers a question,
# it tells the router what exists and where it lives.
skim_notices = (ans.get("stats") or {}).get("skim") or []
if skim_notices:
payload["skim"] = skim_notices[:3]
prov = {"expert": "knowledge", "source": src, prov = {"expert": "knowledge", "source": src,
"note": ("source-verified: verbatim containment in trusted doc" "note": ("source-verified: verbatim containment in trusted doc"
if ans.get("quote") else "no quote — unverified")} if ans.get("quote") else "no quote — unverified")}
+13 -2
View File
@@ -435,6 +435,10 @@ class FloopRun:
# fan-out bookkeeping: entity rows carry the group so the join finds them # fan-out bookkeeping: entity rows carry the group so the join finds them
if q.fan_group: if q.fan_group:
row.provenance["fan_group"] = q.fan_group row.provenance["fan_group"] = q.fan_group
# PR-3: skim notices also land in the run notes — legibility law:
# derived answers render CONTENT, not counts alone
for n in (row.payload.get("skim") or [])[:2]:
self.notes.append(f"{q.qid}: skim: {n[:150]}")
self.table.append(row) self.table.append(row)
if str(row.payload.get("value", "")).strip().upper() == "UNKNOWN": if str(row.payload.get("value", "")).strip().upper() == "UNKNOWN":
q.status = "failed" q.status = "failed"
@@ -445,7 +449,9 @@ class FloopRun:
def _context(self, q: OpenQuestion) -> str: def _context(self, q: OpenQuestion) -> str:
"""What the router sees. A list row renders its ITEMS — 'E1: 50' is """What the router sees. A list row renders its ITEMS — 'E1: 50' is
an ambiguous scalar that routes 'those countries' questions to the an ambiguous scalar that routes 'those countries' questions to the
user; 'E1: list of 50 items: Albania, ...' answers them.""" user; 'E1: list of 50 items: Albania, ...' answers them. Skim notices
(PR-3) render as 'seen in passing' pointers — the router knows what
exists and where it lives, without treating it as answered evidence."""
def render(r) -> str: def render(r) -> str:
if isinstance(r.payload.get("list_items"), list): if isinstance(r.payload.get("list_items"), list):
return (f"list of {r.payload['list_count']} items: " return (f"list of {r.payload['list_count']} items: "
@@ -453,9 +459,12 @@ class FloopRun:
return str(r.payload.get("value", r.payload.get("quote", ""))) return str(r.payload.get("value", r.payload.get("quote", "")))
lines = [] lines = []
notices = []
for d in q.deps: for d in q.deps:
for r in self.table.for_question(d): for r in self.table.for_question(d):
lines.append(f"{r.eid} (answers {r.qid}): {render(r)}") lines.append(f"{r.eid} (answers {r.qid}): {render(r)}")
for n in (r.payload.get("skim") or [])[:2]:
notices.append(f"seen in passing ({r.eid}): {n}")
if not lines: if not lines:
# no declared deps: the router must still SEE what the machine # no declared deps: the router must still SEE what the machine
# holds — an empty context routes referential questions to the # holds — an empty context routes referential questions to the
@@ -464,7 +473,9 @@ class FloopRun:
if r.retracted: if r.retracted:
continue continue
lines.append(f"{r.eid} (answers {r.qid}): {render(r)}") lines.append(f"{r.eid} (answers {r.qid}): {render(r)}")
return "\n".join(lines[:8]) for n in (r.payload.get("skim") or [])[:2]:
notices.append(f"seen in passing ({r.eid}): {n}")
return "\n".join(lines[:8] + notices[:4])
# ---- answer ------------------------------------------------------------ # ---- answer ------------------------------------------------------------
+211 -90
View File
@@ -25,9 +25,10 @@ from .checks import check_candidate, quote_containment
from .chunker import chunk_page from .chunker import chunk_page
from .skim import find_quantities, skim_article from .skim import find_quantities, skim_article
from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature, from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature,
TranslateSignature, VerifyCountSignature, parse_facts) SkimPromoteSignature, TranslateSignature,
VerifyCountSignature, parse_facts)
from .store import KnowledgeStore, norm_name from .store import KnowledgeStore, norm_name
from .wiki import WikipediaClient, WikiPage, resolve_convert from .wiki import WikipediaClient, WikiPage, WikiTable, resolve_convert
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+") WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
@@ -62,8 +63,15 @@ class KnowledgeExpert:
self.translate = dspy.Predict(TranslateSignature) self.translate = dspy.Predict(TranslateSignature)
self.select_table = dspy.Predict(SelectTableSignature) self.select_table = dspy.Predict(SelectTableSignature)
self.verify_count = dspy.Predict(VerifyCountSignature) self.verify_count = dspy.Predict(VerifyCountSignature)
self.skim_promote = dspy.Predict(SkimPromoteSignature)
self._checked = 0 self._checked = 0
self._merged = 0 self._merged = 0
# skim notices accumulated this CALL (PR-3): what the fetched
# articles contained beyond the current question's answer
self._skim_notices: list[str] = []
# ambiguous leads (quantity tables with no goal-vocabulary match)
# pending the bounded promotion decision
self._skim_leads: list[tuple[WikiPage, WikiTable]] = []
# ---- helpers ----------------------------------------------------------- # ---- helpers -----------------------------------------------------------
def _log(self, text: str, think: bool = False) -> None: def _log(self, text: str, think: bool = False) -> None:
@@ -139,6 +147,11 @@ class KnowledgeExpert:
kws = self._keywords(question) kws = self._keywords(question)
goal_terms = self._keywords(parent_question) if parent_question else [] goal_terms = self._keywords(parent_question) if parent_question else []
self._current_goal_terms = goal_terms # the harvest reads these self._current_goal_terms = goal_terms # the harvest reads these
self._current_goal_question = parent_question or question
# per-CALL skim state (PR-3): notices for the machine + ambiguous
# leads pending the bounded promotion decision
self._skim_notices: list[str] = []
self._skim_leads: list[tuple[WikiPage, object]] = []
ev_entities = [e for e in self._expected_entities(evidence or "")][:8] ev_entities = [e for e in self._expected_entities(evidence or "")][:8]
# SEEN-INDEX (PR-2): articles already fetched this RUN — consulted # SEEN-INDEX (PR-2): articles already fetched this RUN — consulted
# before network search so a later question pays zero re-fetch # before network search so a later question pays zero re-fetch
@@ -260,6 +273,16 @@ class KnowledgeExpert:
self._log(f"skim {page.title}: {len(sheet.tables)} tables, " self._log(f"skim {page.title}: {len(sheet.tables)} tables, "
f"{len(sheet.infobox_quantities)} infobox quantities, " f"{len(sheet.infobox_quantities)} infobox quantities, "
f"{len(sheet.link_candidates)} link candidates", think=True) f"{len(sheet.link_candidates)} link candidates", think=True)
# PR-3 — the skim notice: goal-relevant surfaces seen in passing,
# so later steps (router context, run notes) know what exists
# and where it lives. Filtered to goal signals: the notice is a
# pointer, not a dump.
notice = sheet.notice()
if notice:
goal_signal = (any(gt in notice.casefold() for gt in goal_terms)
or any(find_quantities(notice)))
if goal_signal or not goal_terms:
self._skim_notices.append(notice)
if self.cfg.skim_link_queue: if self.cfg.skim_link_queue:
for link in sheet.link_candidates: for link in sheet.link_candidates:
if link not in self._link_queue: if link not in self._link_queue:
@@ -267,6 +290,10 @@ class KnowledgeExpert:
# PR-2 — the opportunistic harvest: goal-relevant side-tables # PR-2 — the opportunistic harvest: goal-relevant side-tables
# seen in passing become typed edges (zero LLM, containment law) # seen in passing become typed edges (zero LLM, containment law)
self._harvest_side_tables(page, sheet, question, evidence) self._harvest_side_tables(page, sheet, question, evidence)
# PR-3 — bounded promotion of ambiguous leads (one LLM call,
# only when leads exist): promoted tables ingest through the
# same containment-checked path as the deterministic harvest
self._promote_leads(evidence, charge_llm)
# LIST path: one SELECT TABLE call per article; on hit, ingest ALL # LIST path: one SELECT TABLE call per article; on hit, ingest ALL
# rows and answer by aggregation (no extract calls, no gate) # rows and answer by aggregation (no extract calls, no gate)
if list_mode and page.tables: if list_mode and page.tables:
@@ -275,7 +302,8 @@ class KnowledgeExpert:
self._log(f"early exit after {page.title}: list " self._log(f"early exit after {page.title}: list "
f"({ans['list_count']} items)", think=True) f"({ans['list_count']} items)", think=True)
return {**ans, "source": "knowledge_graph", return {**ans, "source": "knowledge_graph",
"stats": {"pages": [p.title for p in pages]}} "stats": {**self._skim_stats(pages),
"skim": self._skim_notices}}
# refused by the guard: wrong article's list — keep gathering # refused by the guard: wrong article's list — keep gathering
# EARLY EXIT: one article at a time; if the KG already answers, # EARLY EXIT: one article at a time; if the KG already answers,
# stop spending calls (the gather exists to fill the gap, not to # stop spending calls (the gather exists to fill the gap, not to
@@ -288,7 +316,8 @@ class KnowledgeExpert:
if hit is not None: if hit is not None:
self._log(f"early exit after {page.title}: set {hit}", think=True) self._log(f"early exit after {page.title}: set {hit}", think=True)
return {**self._serve_set(hit, question), "source": "knowledge_graph", return {**self._serve_set(hit, question), "source": "knowledge_graph",
"stats": {"pages": [p.title for p in pages]}} "stats": {**self._skim_stats(pages),
"skim": self._skim_notices}}
else: else:
answer = self._answer_from_rows( answer = self._answer_from_rows(
question, self.store.probe(probe_seeds), charge_llm) question, self.store.probe(probe_seeds), charge_llm)
@@ -296,7 +325,8 @@ class KnowledgeExpert:
self._log(f"early exit after {page.title}: " self._log(f"early exit after {page.title}: "
f"{answer['value'][:60]}", think=True) f"{answer['value'][:60]}", think=True)
return {**answer, "source": "knowledge_graph", return {**answer, "source": "knowledge_graph",
"stats": {"pages": [p.title for p in pages]}} "stats": {**self._skim_stats(pages),
"skim": self._skim_notices}}
# 5-7. remaining pages already processed inline via _process_page # 5-7. remaining pages already processed inline via _process_page
# (early exit); fall through to the final re-probe and answer. # (early exit); fall through to the final re-probe and answer.
@@ -307,10 +337,16 @@ class KnowledgeExpert:
answer = self._answer_from_rows(question, rows, charge_llm) answer = self._answer_from_rows(question, rows, charge_llm)
src = "knowledge_graph" if answer["value"].upper() != "UNKNOWN" else "wikipedia_miss" src = "knowledge_graph" if answer["value"].upper() != "UNKNOWN" else "wikipedia_miss"
return {**answer, "source": src, return {**answer, "source": src,
"stats": {"checked": self._checked, "merged": self._merged, "stats": {**self._skim_stats(pages),
"pages": [p.title for p in pages], "checked": self._checked, "merged": self._merged,
"skim": self._skim_notices,
"elapsed_s": round(time.time() - t0, 1)}} "elapsed_s": round(time.time() - t0, 1)}}
def _skim_stats(self, pages: list[WikiPage]) -> dict:
"""stats shared by every return path: pages seen + link queue state."""
return {"pages": [p.title for p in pages],
"link_queue": len(self._link_queue)}
def _expected_entities(self, evidence: str) -> list[str]: def _expected_entities(self, evidence: str) -> list[str]:
"""Entities the parent's evidence already names — 'the three longest """Entities the parent's evidence already names — 'the three longest
rivers' means the answer's members must be among them. Extracted rivers' means the answer's members must be among them. Extracted
@@ -498,87 +534,13 @@ class KnowledgeExpert:
"coverage": coverage, "coverage": coverage,
} }
def _harvest_side_tables(self, page: WikiPage, sheet, question: str, def _ingest_scalar_table(self, page: WikiPage, t, ent_i: int,
evidence: str) -> int: val_i: int) -> int:
"""PR-2 — the opportunistic harvest: goal-relevant tables seen in """Shared row ingestion for the skim paths (harvest + promote):
passing are ingested as typed rows, zero LLM (KNOWLEDGE.md §7). every row becomes a scalar edge — subject = entity cell, relation =
value-column header, object = value + UNIT (the unit lives in the
A table is harvested when its caption/header carries a GOAL term or caption), quote = the verbatim stored row line, containment against
quantity-unit signal AND its entity column overlaps the entities the the stored table text. Zero LLM; the verbatim law is kept."""
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 "")) cap_q = find_quantities(resolve_convert(t.caption or ""))
unit = cap_q[0].split(" ", 1)[1] if cap_q else "" unit = cap_q[0].split(" ", 1)[1] if cap_q else ""
doc_id = self.store.add_document( doc_id = self.store.add_document(
@@ -610,11 +572,170 @@ class KnowledgeExpert:
self._merged += 1 self._merged += 1
merged += 1 merged += 1
if merged: if merged:
self._log(f"skim harvest: {merged} rows of table {t.idx} " self._log(f"skim ingest: {merged} rows of table {t.idx} "
f"({page.title}) ingested as '{rel}' edges", think=True) f"({page.title}) as '{rel}' edges", think=True)
return merged
def _entity_overlap_count(self, t, ent_i: int, expected: list[str]) -> \
tuple[int, int]:
"""(overlap, members) — how many of the table's entity-column members
the parent's evidence names, and how many members there are."""
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]
if not expected:
return 0, len(members)
en = {norm_name(e) for e in expected}
return sum(1 for m in members if norm_name(m) in en), len(members)
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 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 via _ingest_scalar_table
(verbatim quote, containment, unit from the caption). Deterministic
detection; quantity tables with no goal-vocabulary match are queued
as leads for PR-3's bounded promotion, never guessed here."""
if not self.cfg.skim_harvest:
return 0
expected = self._expected_entities(evidence or "")
goal_terms = self._current_goal_terms or []
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 for the bounded promotion (PR-3),
# never ingested on the unit pattern alone — and the
# seen-index lets a later question come back for it
self._skim_leads.append((page, t))
self._log(f"skim harvest: table {t.idx} of {page.title}: "
f"quantity signal without a goal term — queued "
f"as lead", 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
overlap, nm = self._entity_overlap_count(t, ent_i, expected)
if expected and overlap == 0 and nm >= 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}/{nm} entity overlap — skipped",
think=True)
continue
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
if merged:
harvested += 1 harvested += 1
return harvested return harvested
def _promote_leads(self, evidence: str, charge_llm) -> int:
"""PR-3 — the bounded promotion of ambiguous leads: quantity tables
with no goal-vocabulary match, decided by ONE LLM call per fetched
page that has leads (≤ max_articles per knowledge call, only when
leads exist — most pages have none). The call sees the tables'
IDENTITY (caption/headers/row count/quantity signals — never the
rows). The law split stands: the LLM proposes (which table is about
the goal), fixed code disposes — a promoted table still passes the
entity-overlap check and ingests through the same containment-checked
path as the deterministic harvest. Runs inside the fetch loop, BEFORE
the early-exit checks: leads die with the call otherwise (a later
question only re-harvests pages its own search surfaces again)."""
if not self._skim_leads:
return 0
if not self.cfg.skim_harvest:
self._skim_leads = []
return 0
expected = self._expected_entities(evidence or "")
# group by page; each lead gets a GLOBAL line id (two pages can both
# have a 'table 1' — the idx alone would collide in the lookup)
leads: list[tuple[WikiPage, object]] = self._skim_leads
rendered = []
lookup: dict[int, tuple[WikiPage, object]] = {}
for lid, (page, t) in enumerate(leads, start=1):
cap = resolve_convert(t.caption or "") or "(no caption)"
qtys = find_quantities("\n".join(t.text_lines()))[:3]
rendered.append(
f"{lid} | {cap} | header: {', '.join(t.header[:6])} | "
f"rows: {t.total_rows} | quantities: {', '.join(qtys) or 'none'}")
lookup[lid] = (page, t)
if not rendered:
return 0
if charge_llm:
charge_llm()
pred = self.skim_promote(
goal=self._current_goal_question,
entities=", ".join(expected[:8]),
tables="\n".join(rendered))
promoted = 0
for line in (pred.decision or "").strip().splitlines():
m = re.match(r"\s*(\d+)\s*:\s*(YES|NO)\s*(.*)$", line.strip(),
flags=re.I)
if not m:
continue
idx, verdict, col = int(m.group(1)), m.group(2).upper(), m.group(3).strip()
got = lookup.get(idx)
if verdict != "YES" or got is None:
continue
page, t = got
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 col and col.casefold() in h.casefold()), 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:
continue
overlap, nm = self._entity_overlap_count(t, ent_i, expected)
if expected and overlap == 0 and nm >= 2:
self._log(f"skim promote: table {idx} ({page.title}): LLM said "
f"YES but {overlap}/{nm} entity overlap — refused",
think=True)
continue
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
if merged:
self._log(f"skim promote: {merged} rows of table {idx} "
f"({page.title}) ingested (LLM-proposed)", think=True)
promoted += 1
self._skim_leads = [] # consumed: bounded, never re-asked
return promoted
def _process_page(self, page: WikiPage, question: str, kws: list[str], def _process_page(self, page: WikiPage, question: str, kws: list[str],
charge_llm, goal_terms: list[str] | None = None) -> int: charge_llm, goal_terms: list[str] | None = None) -> int:
"""Chunk -> gate -> RANK (skim) -> extract -> check -> merge for ONE """Chunk -> gate -> RANK (skim) -> extract -> check -> merge for ONE
+16
View File
@@ -80,6 +80,22 @@ class SelectTableSignature(dspy.Signature):
origin_question: str = dspy.OutputField(desc="the question verbatim, for provenance; empty if NONE") origin_question: str = dspy.OutputField(desc="the question verbatim, for provenance; empty if NONE")
class SkimPromoteSignature(dspy.Signature):
"""You are the SKIM PROMOTE step of a knowledge machine. While fetching
articles for one question, tables were seen in passing that carry
quantity data but match none of the goal's words (the goal's vocabulary
and the table's words may differ — 'water flow' vs 'Flow at the mouth').
Given the run's goal, the entities it is about, and the tables' identity
(caption, headers, row count, quantity signals — NOT the rows), decide
per table whether it holds data about those entities for the goal.
Output one line per table: 'idx: YES <column>' or 'idx: NO' — the column
is the header holding the goal's values."""
goal: str = dspy.InputField(desc="the run's overall goal question")
entities: str = dspy.InputField(desc="the entities the goal is about, comma separated; may be empty")
tables: str = dspy.InputField(desc="one line per table: 'idx | caption | header: a, b, c | rows: N | quantities: x, y'")
decision: str = dspy.OutputField(desc="one line per table: 'idx: YES <column>' or 'idx: NO'")
def parse_facts(raw: str) -> list[dict]: def parse_facts(raw: str) -> list[dict]:
"""Parse the extractor's piped lines; malformed lines are dropped+counted. """Parse the extractor's piped lines; malformed lines are dropped+counted.
+3 -2
View File
@@ -24,9 +24,10 @@ from dataclasses import dataclass, field
from .wiki import resolve_convert from .wiki import resolve_convert
# --- quantity-unit patterns (the vocabulary-independent signal) ------------ # --- quantity-unit patterns (the vocabulary-independent signal) ------------
# number (with , or . thousands, optional decimals) followed by a unit token # number (thousands with , or ., optional decimals; OR plain digits — '1540'
# and '1000' carry no thousands separator) followed by a unit token
_QTY_RE = re.compile( _QTY_RE = re.compile(
r"\b(\d{1,3}(?:[.,]\d{3})*(?:\.\d+)?)" # number, , thousands, opt decimals r"\b(\d{1,3}(?:[.,]\d{3})*(?:\.\d+)?|\d+(?:\.\d+)?)"
r"[\s\u00a0-]*(m3/s|m³/s|cu\s*ft/s|cuft/s|ft3/s" r"[\s\u00a0-]*(m3/s|m³/s|cu\s*ft/s|cuft/s|ft3/s"
r"|km2|km²|km|mi2|mi²|mi|kg|mm|cm|m|s|%)\b", r"|km2|km²|km|mi2|mi²|mi|kg|mm|cm|m|s|%)\b",
re.I) re.I)
+6
View File
@@ -25,6 +25,12 @@ def make_expert(store: KnowledgeStore) -> KnowledgeExpert:
e._log = lambda *a, **k: None e._log = lambda *a, **k: None
e._checked = 0 e._checked = 0
e._merged = 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 return e
+155
View File
@@ -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")