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="",
|
||||
)
|
||||
Reference in New Issue
Block a user