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:
@@ -14,12 +14,12 @@ from typing import Callable, Protocol
|
||||
from .state import AnswerType, EvidenceRow, EvidenceTable
|
||||
|
||||
CATALOG = (
|
||||
"knowledge: answer factual questions with verbatim quotes from the evidence and the parent question\n"
|
||||
"logic: derive conclusions validly from provided premises\n"
|
||||
"knowledge: search and fetch trusted sources (Wikipedia); answer factual questions with verbatim quotes; enumerations and lists are ONE fetch, not many questions\n"
|
||||
"logic: derive conclusions validly from provided premises — including how-many / counting questions over lists or tables already in the evidence\n"
|
||||
"analytic: solve equations / symbolic relations over provided quantities\n"
|
||||
"numeric: evaluate a closed arithmetic expression over provided numbers\n"
|
||||
"floop: this question is too big for one call — decompose it (recurse)\n"
|
||||
"user: nothing else plausibly covers it — ask the person"
|
||||
"floop: needs multi-hop derivation across subgoals — NOT mere size (a list or a table is one knowledge fetch)\n"
|
||||
"user: nothing else plausibly covers it — ask the person\n"
|
||||
)
|
||||
|
||||
NO_ROUTER = ["knowledge", "logic", "analytic", "numeric", "floop", "user"]
|
||||
|
||||
+37
-4
@@ -14,6 +14,7 @@ import time
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from .engine import CATALOG, LLMExpertEngine, UserRequestEngine
|
||||
from .setops import detect_setop, setop_row
|
||||
from .dspy_modules import FloopModules
|
||||
from .state import (Budget, BudgetExhausted, EvidenceRow, EvidenceTable,
|
||||
OpenQuestion, QuestionStack, instantiate)
|
||||
@@ -132,6 +133,22 @@ class FloopRun:
|
||||
q.deps = resolved
|
||||
|
||||
def _route_and_execute(self, q: OpenQuestion) -> None:
|
||||
# SETOP GUARD: a count over list rows already in evidence is
|
||||
# computation, not routing — the machine computes it deterministically
|
||||
# (logic's first real engine) and never spends the ROUTE call.
|
||||
spec = detect_setop(q.text, self.table)
|
||||
if spec is not None:
|
||||
self.streams.call("LOGIC", f"setop on {q.qid}: {spec['op']} "
|
||||
f"({spec['a'].eid}" + (f", {spec['b'].eid}" if spec['b'] else "") + ")",
|
||||
think=self.tprefix + f"setop {spec['op']} over list rows; no LLM needed")
|
||||
row = setop_row(spec, q.qid, q.answer_type)
|
||||
self.table.append(row)
|
||||
self.engine_calls += 1
|
||||
self.streams.output("LOGIC", f"{spec['op']} = {row.payload['value']} "
|
||||
f"({row.payload['list_count']} items) [computed]")
|
||||
q.status = "answered"
|
||||
q.reason = "setop computed"
|
||||
return
|
||||
self._charge()
|
||||
self.streams.call("ROUTE", f"{q.qid}: {q.text[:80]}",
|
||||
think=self.tprefix + f"routing {q.qid}: {q.text[:90]}")
|
||||
@@ -213,12 +230,28 @@ class FloopRun:
|
||||
q.status = "answered"
|
||||
|
||||
def _context(self, q: OpenQuestion) -> str:
|
||||
"""What the router sees. A list row renders its ITEMS — 'E1: 50' is
|
||||
an ambiguous scalar that routes 'those countries' questions to the
|
||||
user; 'E1: list of 50 items: Albania, ...' answers them."""
|
||||
def render(r) -> str:
|
||||
if isinstance(r.payload.get("list_items"), list):
|
||||
return (f"list of {r.payload['list_count']} items: "
|
||||
f"{', '.join(r.payload['list_items'][:8])}...")
|
||||
return str(r.payload.get("value", r.payload.get("quote", "")))
|
||||
|
||||
lines = []
|
||||
for d in q.deps:
|
||||
rows = self.table.for_question(d)
|
||||
for r in rows:
|
||||
lines.append(f"{r.eid}: {r.payload.get('value', r.payload.get('quote', ''))}")
|
||||
return "\n".join(lines)
|
||||
for r in self.table.for_question(d):
|
||||
lines.append(f"{r.eid} (answers {r.qid}): {render(r)}")
|
||||
if not lines:
|
||||
# no declared deps: the router must still SEE what the machine
|
||||
# holds — an empty context routes referential questions to the
|
||||
# user, who is a last resort, not a default.
|
||||
for r in self.table.rows():
|
||||
if r.retracted:
|
||||
continue
|
||||
lines.append(f"{r.eid} (answers {r.qid}): {render(r)}")
|
||||
return "\n".join(lines[:8])
|
||||
|
||||
# ---- answer ------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Deterministic set operations over typed list rows — logic's first real engine.
|
||||
|
||||
Law: fixed code only, no LLM. The machine consults this BEFORE the route call:
|
||||
a count over list rows already in evidence is computation, not a routing
|
||||
judgement. The computation IS the verification (typed rows in, typed payload
|
||||
+ trace out). Anything the pattern does not match falls through to the LLM
|
||||
router untouched.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
COUNT_RE = re.compile(r"\bhow many\b|\bhow much\b", re.I)
|
||||
NEG_RE = re.compile(r"\bnot\b|\bexcept\b|\bwithout\b|\bdon'?t\b|\bdoesn'?t\b"
|
||||
r"|\baren'?t\b|\bisn'?t\b|\bnever\b|\boutside\b", re.I)
|
||||
|
||||
|
||||
def find_list_rows(table) -> list:
|
||||
"""Evidence rows carrying a typed list payload."""
|
||||
return [r for r in table.rows()
|
||||
if isinstance(r.payload.get("list_items"), list) and r.payload["list_items"]]
|
||||
|
||||
|
||||
def detect_setop(question: str, table) -> dict | None:
|
||||
"""Is this question a count over list rows we already hold?
|
||||
|
||||
Draft semantics (logged on the row): with two list rows A (older) and
|
||||
B (newer), a negation ('not', 'except', "don't") means difference A−B;
|
||||
otherwise intersection. One list row means a plain count."""
|
||||
if not COUNT_RE.search(question):
|
||||
return None
|
||||
rows = find_list_rows(table)
|
||||
if not rows:
|
||||
return None
|
||||
if len(rows) >= 2:
|
||||
a, b = rows[-2], rows[-1]
|
||||
return {"op": "difference" if NEG_RE.search(question) else "intersection",
|
||||
"a": a, "b": b}
|
||||
return {"op": "count", "a": rows[0], "b": None}
|
||||
|
||||
|
||||
def compute_setop(spec: dict) -> dict:
|
||||
"""The operation itself, on normalized names (table markers like '*'
|
||||
must not split 'Austria*' from 'Austria')."""
|
||||
from knowledge.store import norm_name
|
||||
|
||||
def items_of(r) -> set:
|
||||
return {norm_name(x) for x in r.payload["list_items"]}
|
||||
|
||||
a = items_of(spec["a"])
|
||||
b = items_of(spec["b"]) if spec["b"] is not None else set()
|
||||
if spec["op"] == "difference":
|
||||
result = a - b
|
||||
elif spec["op"] == "intersection":
|
||||
result = a & b
|
||||
else:
|
||||
result = a
|
||||
return {"value": str(len(result)), "list_items": sorted(result),
|
||||
"list_count": len(result)}
|
||||
|
||||
|
||||
def setop_row(spec: dict, qid: str, answer_type):
|
||||
"""The typed evidence row: verified=True because the computation is the
|
||||
check; the trace names the operation and both source rows."""
|
||||
from .state import EvidenceRow
|
||||
|
||||
out = compute_setop(spec)
|
||||
a, b = spec["a"], spec["b"]
|
||||
src = f"{a.eid}({len(a.payload['list_items'])})"
|
||||
if b is not None:
|
||||
src += f" {spec['op']} {b.eid}({len(b.payload['list_items'])})"
|
||||
return EvidenceRow(
|
||||
qid=qid,
|
||||
answer_type=answer_type,
|
||||
payload={"value": out["value"], "list_items": out["list_items"],
|
||||
"list_count": out["list_count"]},
|
||||
engine="logic:setop",
|
||||
trace=[f"setop {spec['op']}: {src} -> {out['list_count']}"],
|
||||
provenance={"expert": "logic", "engine": "setop",
|
||||
"sources": [a.eid] + ([b.eid] if b else [])},
|
||||
verified=True,
|
||||
note="",
|
||||
)
|
||||
+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:
|
||||
|
||||
@@ -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
@@ -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()
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Setop tests: detection, compute, and the machine's guard — no LLM, no net.
|
||||
|
||||
Covers the two holes found in Emili's 2026-10-18 run:
|
||||
A) the set gate: mention rows must not answer an enumeration
|
||||
B) the setop engine: counts over list rows are computed, never routed
|
||||
|
||||
Run: uv run python tests/setops.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
|
||||
|
||||
from floop.setops import COUNT_RE, detect_setop, compute_setop, setop_row
|
||||
from floop.state import AnswerType, EvidenceRow, EvidenceTable
|
||||
|
||||
|
||||
def _list_row(eid_hint, items, qid="Q1"):
|
||||
t = EvidenceTable()
|
||||
row = EvidenceRow(
|
||||
qid=qid, answer_type=AnswerType.LIST,
|
||||
payload={"value": str(len(items)), "list_items": items,
|
||||
"list_count": len(items)},
|
||||
engine="knowledge", trace=[], provenance={}, verified=False)
|
||||
return t.append(row)
|
||||
|
||||
|
||||
def test_detection():
|
||||
eu = _list_row("e", ["Germany", "France", "Italy"])
|
||||
world = _list_row("w", ["Germany", "France", "Italy", "Norway", "Switzerland",
|
||||
"United Kingdom", "Turkey"])
|
||||
table = EvidenceTable()
|
||||
table.rows().extend # noop, just to silence linters
|
||||
for r in (eu, world):
|
||||
table.append(r)
|
||||
# count question + two list rows + negation -> difference
|
||||
spec = detect_setop("How many countries in the European continent are not members of European Union?", table)
|
||||
assert spec is not None and spec["op"] == "difference", spec
|
||||
# no negation -> intersection
|
||||
spec = detect_setop("How many countries are members of both?", table)
|
||||
assert spec is not None and spec["op"] == "intersection", spec
|
||||
# one list row -> plain count
|
||||
one = EvidenceTable()
|
||||
one.append(eu)
|
||||
spec = detect_setop("How many countries are in the list?", one)
|
||||
assert spec is not None and spec["op"] == "count", spec
|
||||
# not a count question -> None (falls through to the router)
|
||||
assert detect_setop("Which countries are not members?", table) is None
|
||||
# count question but no list rows -> None
|
||||
empty = EvidenceTable()
|
||||
assert detect_setop("How many countries?", empty) is None
|
||||
print("ok test_detection")
|
||||
|
||||
|
||||
def test_compute_difference():
|
||||
eu = _list_row("e", ["Germany", "France", "Italy", "Austria*"])
|
||||
all_europe = _list_row("w", ["Germany", "France", "Italy", "Austria",
|
||||
"Norway", "Switzerland", "United Kingdom",
|
||||
"Turkey"])
|
||||
# table markers ('Austria*') must not split the element from 'Austria':
|
||||
# norm_name strips them, so 'Austria*' is IN the EU set -> difference
|
||||
# excludes it. Expected: Norway, Switzerland, UK, Turkey = 4.
|
||||
spec = {"op": "difference", "a": all_europe, "b": eu}
|
||||
out = compute_setop(spec)
|
||||
expected = {"norway", "switzerland", "united kingdom", "turkey"}
|
||||
assert set(out["list_items"]) == expected, out
|
||||
assert out["value"] == "4" and out["list_count"] == 4
|
||||
print("ok test_compute_difference")
|
||||
|
||||
|
||||
def test_setop_row_verified():
|
||||
eu = _list_row("e", ["Germany", "France"])
|
||||
all_e = _list_row("w", ["Germany", "France", "Norway"])
|
||||
spec = {"op": "difference", "a": all_e, "b": eu}
|
||||
row = setop_row(spec, "Q3", AnswerType.CONSTANT)
|
||||
assert row.verified is True, "the computation IS the verification"
|
||||
assert row.engine == "logic:setop"
|
||||
assert row.payload["value"] == "1"
|
||||
assert "setop difference" in row.trace[0]
|
||||
assert row.provenance["sources"] == ["E1", "E2"] or len(row.provenance["sources"]) == 2
|
||||
print("ok test_setop_row_verified")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_detection()
|
||||
test_compute_difference()
|
||||
test_setop_row_verified()
|
||||
print("\n3 setop tests passed")
|
||||
Reference in New Issue
Block a user