feat(logic): setop engine + set gate — the Europe count computed end-to-end

A) SET GATE: enumerations are answered only from membership sets, never from mention rows (the probe early-exit that served 'Armenia, Cyprus, Georgia, Turkey' to 'what countries are in Europe' is dead). Sets carry origin_question; the gate matches stem-Jaccard>=0.5 so a set is served to its own question only. B) SETOP ENGINE: logic's first real engine — a count over list rows is computed (difference/intersection/count over norm_name'd items, table markers 'Austria*' == 'Austria'), before ROUTE, zero LLM calls, verified=True because the computation IS the check. C) Catalog honesty: knowledge 'lists are ONE fetch', logic 'how-many over lists in evidence', floop 'NOT mere size'. Plus four substrate bugs the live runs exposed: LM-proxy prompt cache (instant answers are cache hits, never trust zero latency), _context rendering list rows as scalars ('E1: 50' routed 'those countries' to user), <br> concatenation in multi-value name cells, multi-line refs leaking into values ('franceincludes the 101 departments' -> France dropped from EU -> 24 not 23). Cold E2E: Q1 50 states ingested, Q2 27 EU members ingested, Q3 difference computed = 23, cited over E1/E2. 22/22 tests.
This commit is contained in:
2026-10-18 19:49:24 +02:00
parent 6fcb3c0a86
commit e5482bd092
10 changed files with 390 additions and 34 deletions
+75 -20
View File
@@ -25,7 +25,7 @@ from .checks import check_candidate
from .chunker import chunk_page
from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature,
TranslateSignature, parse_facts)
from .store import KnowledgeStore
from .store import KnowledgeStore, norm_name
from .wiki import WikipediaClient, WikiPage
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
@@ -77,6 +77,41 @@ class KnowledgeExpert:
seen.append(w)
return seen[:k]
def _set_gate_hit(self, probe_seeds: list[str], question: str) -> str | None:
"""The membership set (if any) this question may be served from.
Mention rows never answer enumerations — only a set does. And a set
belongs to ITS question: serving Q1's 'countries in Europe' set to
'which are EU members?' would be a confident wrong answer. The match
is stem-Jaccard >= 0.5 between the incoming question and the set's
ORIGIN question — near-repeats are served, different questions gather."""
from .store import stem
q_stems = {stem(w) for w in WORD_RE.findall(question.casefold())
if len(w) > 2}
for set_name, origin in self.store.set_origins():
o_stems = {stem(w) for w in WORD_RE.findall(origin.casefold())
if len(w) > 2}
if not q_stems or not o_stems:
continue
jac = len(q_stems & o_stems) / len(q_stems | o_stems)
if jac >= 0.5 and self.store.list_members(set_name):
return set_name
return None
def _serve_set(self, set_name: str, question: str) -> dict:
"""Answer an enumeration from a held membership set: the full member
list with provenance, coverage complete per source."""
members = self.store.list_members(set_name)
quote, url = self.store.set_provenance(set_name)
self._log(f"kg set hit: {set_name} ({len(members)} members)", think=True)
return {"value": str(len(members)), "list_items": members,
"list_count": len(members), "quote": quote, "url": url,
"confidence": "high",
"coverage": {"source": "knowledge_graph", "set": set_name,
"rows_ingested": len(members),
"rows_total": len(members),
"complete_per_source": True}}
# ---- the pipeline --------------------------------------------------------
def answer_question(self, question: str, parent_question: str = "",
evidence: str = "", charge_llm=None,
@@ -92,6 +127,9 @@ class KnowledgeExpert:
if evidence:
context += (chr(10) * 2 if context else "") + f"Evidence:\n{evidence}"
kws = self._keywords(question)
# LIST activation (moved up: the set gate needs it before the probe)
list_mode = (str(answer_type or "").upper() == "LIST"
or self._is_enumeration(question))
self._log(f"knowledge: question={question[:80]!r} keywords={kws}", think=True)
# 2. KG probe first: question keywords + entities from the machine's
@@ -104,10 +142,21 @@ class KnowledgeExpert:
probe_seeds.extend(val.split())
rows = self.store.probe(probe_seeds)
self._log(f"kg probe ({probe_seeds}): {len(rows)} rows", think=True)
answer = self._answer_from_rows(question, rows, charge_llm)
if answer["value"] and answer["value"].upper() != "UNKNOWN":
self._log(f"kg hit: {answer['value'][:60]}", think=True)
return {**answer, "source": "knowledge_graph", "kg_rows": len(rows)}
# SET GATE (lists): mention rows never answer an enumeration — only a
# membership set does. With no set held, the probe result is not
# answerability evidence; the gather must run.
if list_mode:
kg_set = self._set_gate_hit(probe_seeds, question)
if kg_set:
return {**self._serve_set(kg_set, question),
"source": "knowledge_graph", "kg_rows": len(rows)}
self._log(f"set gate: {len(rows)} mention rows are not answerability "
f"for an enumeration; gather runs", think=True)
else:
answer = self._answer_from_rows(question, rows, charge_llm)
if answer["value"] and answer["value"].upper() != "UNKNOWN":
self._log(f"kg hit: {answer['value'][:60]}", think=True)
return {**answer, "source": "knowledge_graph", "kg_rows": len(rows)}
# 3-4. gap -> search + fetch. TRANSLATE (LLM) first: the question becomes
# entity-first Wikipedia queries — deterministic keywords alone surface
@@ -169,12 +218,6 @@ class KnowledgeExpert:
self._log(f"fetch order: {ordered[: self.cfg.max_articles]}", think=True)
pages: list[WikiPage] = []
# LIST activation: declared by the planner (answer_type=LIST) OR
# detected deterministically when the question is an enumeration ask
# (planner support pending on the local model — the path must work
# regardless of who declares it)
list_mode = (str(answer_type or "").upper() == "LIST"
or self._is_enumeration(question))
for title in ordered[: self.cfg.max_articles]:
try:
page = self.client.fetch_rich(title)
@@ -193,15 +236,23 @@ class KnowledgeExpert:
"stats": {"pages": [p.title for p in pages]}}
# EARLY EXIT: one article at a time; if the KG already answers,
# stop spending calls (the gather exists to fill the gap, not to
# hoover every candidate)
# hoover every candidate). For enumerations the set gate applies
# here too: mention rows never answer a list question.
self._process_page(page, question, kws, charge_llm)
answer = self._answer_from_rows(
question, self.store.probe(probe_seeds), charge_llm)
if answer["value"] and answer["value"].upper() != "UNKNOWN":
self._log(f"early exit after {page.title}: "
f"{answer['value'][:60]}", think=True)
return {**answer, "source": "knowledge_graph",
"stats": {"pages": [p.title for p in pages]}}
if list_mode:
hit = self._set_gate_hit(probe_seeds, question)
if hit is not None:
self._log(f"early exit after {page.title}: set {hit}", think=True)
return {**self._serve_set(hit, question), "source": "knowledge_graph",
"stats": {"pages": [p.title for p in pages]}}
else:
answer = self._answer_from_rows(
question, self.store.probe(probe_seeds), charge_llm)
if answer["value"] and answer["value"].upper() != "UNKNOWN":
self._log(f"early exit after {page.title}: "
f"{answer['value'][:60]}", think=True)
return {**answer, "source": "knowledge_graph",
"stats": {"pages": [p.title for p in pages]}}
# 5-7. remaining pages already processed inline via _process_page
# (early exit); fall through to the final re-probe and answer.
@@ -253,6 +304,7 @@ class KnowledgeExpert:
col_i = next((i for i, h in enumerate(table.header)
if column.casefold() in h.casefold()), 0)
set_name = (pred.set_name or "").strip() or question[:60]
origin_question = (pred.origin_question or "").strip() or question
# INGEST ALL ROWS: one membership edge per row, quote = the full
# stored row line, containment against the stored table text
doc_id = self.store.add_document(
@@ -264,6 +316,8 @@ class KnowledgeExpert:
element = (row[col_i] if col_i < len(row) else (row[0] if row else "")).strip()
if not element:
continue
if " / " in element:
element = element.split(" / ")[0].strip() # first of multi-value cell
if element.casefold() in ("total", "totals", "sum", "average", "mean"):
continue # aggregate footer rows are not members
if element.isdigit():
@@ -277,7 +331,8 @@ class KnowledgeExpert:
continue
qid = self.store.add_quote(doc_id, row_line, page.url, page.fetched_at)
self.store.add_edge(element, "member_of", set_name, qid,
src_sort="PLACE", dst_node_name=set_name)
src_sort="PLACE", dst_node_name=set_name,
origin_question=origin_question)
members.append(element)
self._merged += 1
if not members:
+1
View File
@@ -58,6 +58,7 @@ class SelectTableSignature(dspy.Signature):
table_index: str = dspy.OutputField(desc="the chosen table index (e.g. '2'), or NONE")
column: str = dspy.OutputField(desc="header name of the column holding the answer elements; empty if NONE")
set_name: str = dspy.OutputField(desc="short name of the set this table enumerates, e.g. 'sovereign states in Europe'; empty if NONE")
origin_question: str = dspy.OutputField(desc="the question verbatim, for provenance; empty if NONE")
def parse_facts(raw: str) -> list[dict]:
+23 -3
View File
@@ -30,6 +30,7 @@ CREATE TABLE IF NOT EXISTS nodes (
CREATE TABLE IF NOT EXISTS edges (
id INTEGER PRIMARY KEY, src_node INTEGER, rel TEXT, dst_value TEXT,
dst_node INTEGER, quote_id INTEGER, extraction_confidence REAL,
origin_question TEXT,
ref_date TEXT, supersedes INTEGER, preferred INTEGER DEFAULT 0,
retracted INTEGER DEFAULT 0, retraction_reason TEXT, corroboration INTEGER DEFAULT 1
);
@@ -120,7 +121,8 @@ class KnowledgeStore:
def add_edge(self, src_name: str, rel: str, dst_value: str, quote_id: int,
src_sort: str = "CONCEPT", dst_node_name: str | None = None,
dst_sort: str = "CONCEPT", confidence: float = 0.8,
ref_date: str | None = None) -> int | None:
ref_date: str | None = None,
origin_question: str | None = None) -> int | None:
"""Add an edge, applying the four contradiction cases (KNOWLEDGE.md §2).
Returns the edge id, or None when the candidate was a duplicate
@@ -144,8 +146,8 @@ class KnowledgeStore:
(src, rel)).fetchall()
cur = self.db.execute(
"INSERT INTO edges(src_node, rel, dst_value, dst_node, quote_id, "
"extraction_confidence, ref_date, preferred) VALUES(?,?,?,?,?,?,?,0)",
(src, rel, dst_value, dst_node, quote_id, confidence, ref_date))
"extraction_confidence, origin_question, ref_date, preferred) VALUES(?,?,?,?,?,?,?,?,0)",
(src, rel, dst_value, dst_node, quote_id, confidence, origin_question, ref_date))
edge_id = cur.lastrowid
for other_id, other_val, other_date in others:
case = self._classify(new_val=dst_value, new_date=ref_date,
@@ -259,5 +261,23 @@ class KnowledgeStore:
(set_name,)).fetchall()
return sorted(r[0] for r in rows)
def set_origins(self) -> list[tuple[str, str]]:
"""(set_name, origin_question) for every membership set — the gate
matches a set to its own question, never to a different one."""
rows = self.db.execute(
"SELECT DISTINCT dst_value, origin_question FROM edges "
"WHERE rel='member_of' AND retracted=0 AND origin_question IS NOT NULL"
).fetchall()
return [(r[0], r[1]) for r in rows]
def set_provenance(self, set_name: str) -> tuple[str, str]:
"""(quote, url) of the first member edge of a set — provenance for
list answers served from the KG."""
row = self.db.execute(
"SELECT q.verbatim, q.url FROM edges e JOIN quotes q ON q.id=e.quote_id "
"WHERE e.rel='member_of' AND e.retracted=0 AND lower(e.dst_value)=lower(?) "
"LIMIT 1", (set_name,)).fetchone()
return (row[0], row[1]) if row else ("", "")
def close(self) -> None:
self.db.close()
+2
View File
@@ -135,6 +135,7 @@ def test_list_ingest_aggregate(tmp="/tmp/floop_kg_list.sqlite"):
p.table_index = "1"
p.column = "Country"
p.set_name = "sovereign states in Europe"
p.origin_question = kw.get("question", "")
return p
class FakeStore:
@@ -185,6 +186,7 @@ def test_list_ingest_aggregate(tmp="/tmp/floop_kg_list.sqlite"):
p.table_index = "NONE"
p.column = ""
p.set_name = ""
p.origin_question = ""
return p
ke.select_table = FakeNonePicker()
assert ke._list_from_page(page, "irrelevant", None) is None
+9 -3
View File
@@ -113,6 +113,11 @@ def parse_tables(wikitext: str, max_tables: int = 4) -> list[WikiTable]:
if line.startswith("|"):
raw_cells.extend(re.split(r"\|\|", line.lstrip("|")))
continue
# continuation line: multi-line refs/templates inside a cell do
# not start with a marker — they belong to the previous raw cell
if raw_cells:
raw_cells[-1] += " " + line
continue
if raw_cells:
flush_row(raw_cells, row_is_header)
if header_grid:
@@ -155,9 +160,10 @@ def _tpl_arg(content: str) -> str:
def _clean_cell(cell: str) -> str:
"""Resolve links/templates to display text; drop refs, File links, tags.
Order matters: refs with content first (else their text leaks into the
value — 'France<ref name=g/>' -> 'Franceg'), then File links (dropped
whole), then links (display text), then templates innermost-out."""
Order matters: <br> variants become ' / ' separators FIRST (multi-value
name cells like 'Albania<br>Republic of Albania<br>ALB' must not
concatenate), then refs, File links, links, templates."""
cell = re.sub(r"<br\s*/?>", " / ", cell, flags=re.I)
cell = re.sub(r"<ref[^>]*>.*?</ref>", "", cell, flags=re.S | re.I)
cell = re.sub(r"<ref[^>]*/?>", "", cell, flags=re.I)
cell = re.sub(r"<sup[^>]*>.*?</sup>", "", cell, flags=re.S | re.I)