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:
+75
-20
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user