machine: fan-out planner + disjointness guard (runs 07/08 lessons)

(a) Disjointness guard (knowledge/expert.py): a LIST ingest whose members
    don't overlap the entities the parent's evidence names is refused; the
    gather continues to the next article. Run-08's 'flow of Po/Adige/Tiber'
    answered by the Amazon from a world-wide table can no longer happen.
(b) Fan-out planner (floop/machine.py): a 'for each' subquestion over a list
    row expands deterministically into N entity questions + one join.
    Top-N bound respected ('those three' over 22 rows -> top 3 by table
    order, logged). The join is a deterministic sum over the entity rows
    (verified=True: computation is its own proof), partial sums named.
    Entity rows are tagged fan_group in provenance so the join finds them.
Also: LIST ingest keeps TABLE ORDER (ranked tables rank; alphabetical sort
      destroyed the ranking) — dict.fromkeys dedup.
Budget: 40 -> 80 (a 3-entity fan-out needs ~3x a scalar question).

Verified live (cold KG, 2 runs): list ingest in table order, slice top-3,
fan-out -> 3 entity questions + join, Po answered with verbatim quote
(1,460 m3/s). 28/28 tests (fan-out expansion+join, top-N slice, guard).
This commit is contained in:
2026-10-19 20:16:01 +02:00
parent 852db78c99
commit 209909e776
6 changed files with 369 additions and 6 deletions
+172 -2
View File
@@ -10,19 +10,26 @@ ALGORITHM.md mapping (v0.1 draft — every STUB is named honestly):
"""
from __future__ import annotations
import re
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)
from .state import (AnswerType, Budget, BudgetExhausted, EvidenceRow,
EvidenceTable, OpenQuestion, QuestionStack, instantiate)
from .stream import RunStreams
EXPERT_ENGINES = ("knowledge", "logic", "analytic", "numeric")
def _fmt_num(x: float) -> str:
"""Deterministic number formatting for computed rows: integers plain,
floats trimmed (no trailing .0)."""
return str(int(x)) if float(x).is_integer() else f"{x:g}"
def _coerce_atype(value) -> "AnswerType":
from .state import AnswerType as AT
if isinstance(value, AT):
@@ -156,6 +163,143 @@ class FloopRun:
resolved.append(created[tok - 1].qid)
q.deps = resolved
# ---- fan-out (the planner's expansion; deterministic guard) --------------
FANOUT_MARK = re.compile(r"\b(for each|of each|per)\b", re.I)
_NUMWORDS = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5,
"six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10,
"eleven": 11, "twelve": 12}
def _fan_items(self, q: OpenQuestion) -> tuple[str, list[str]] | None:
"""The list an entity-fan question iterates over: the LIST row in its
deps, or a scalar comma-list row ('Po, Adige, Tiber'), or the table's
single list row when the text points with 'those/these'. Deterministic
— question shape is the machine's business, never the LLM's."""
for d in q.deps:
for r in self.table.for_question(d):
if isinstance(r.payload.get("list_items"), list) and r.payload["list_items"]:
return r.eid, list(r.payload["list_items"])
val = str(r.payload.get("value", ""))
if val.count(",") >= 1 and len(val) <= 80 and not val.replace(",", "").strip().isdigit():
items = [t.strip() for t in val.split(",") if t.strip()]
if 2 <= len(items) <= 12:
return r.eid, items
if re.search(r"\b(those|these|that)\b", q.text, re.I):
lists = [r for r in self.table.rows()
if isinstance(r.payload.get("list_items"), list)
and r.payload["list_items"] and not r.retracted]
if len(lists) == 1:
return lists[0].eid, list(lists[0].payload["list_items"])
return None
def _fan_count(self, qtext: str) -> int:
"""N when the question bounds the fan: 'those three rivers' -> 3."""
for w, n in self._NUMWORDS.items():
if re.search(rf"\b{w}\b", qtext, re.I):
return n
m = re.search(r"\b(\d{1,2})\b", qtext)
return int(m.group(1)) if m else 0
def _attribute_of(self, qtext: str) -> str:
"""'What is the average annual water flow (discharge) for each of
those rivers?' -> 'average annual water flow (discharge)'."""
m = re.match(r"(?:What is|What are|Which is|Which are)\s+(?:the\s+)?(.+?)"
r"\s+(?:for|of)\s+each", qtext, re.I)
if m:
return m.group(1).strip()
t = re.sub(self.FANOUT_MARK, "", qtext, count=1)
return re.sub(r"\?+$", "", t).strip()[:80]
def _detect_fanout(self, q: OpenQuestion) -> tuple[str, list[str]] | None:
"""A 'for each' subquestion over a known list is N entity questions +
one join — never one knowledge call over all entities at once."""
if not self.FANOUT_MARK.search(q.text):
return None
return self._fan_items(q)
def _expand_fanout(self, q: OpenQuestion, fan: tuple[str, list[str]]) -> None:
list_eid, items = fan
# top-N slice: 'for each of those three rivers' over a 22-row ranked
# table means the TOP 3 by table order (ranked tables rank; the slice
# is honest and logged, the value-ranked top-N is part (c))
n = self._fan_count(q.text)
if n and 0 < n < len(items):
items = items[:n]
self.notes.append(f"{q.qid}: fan-out sliced to top {n} of "
f"{len(fan[1])} by table order (ranked list assumed)")
attribute = self._attribute_of(q.text)
self.streams.call("FANOUT", f"expanding {q.qid} into {len(items)} entity questions",
think=self.tprefix + f"fan-out: {q.qid} over {list_eid}'s "
f"{len(items)} items — one question per item, then a join")
# 1) one entity question per item (no deps: the list row already exists)
entity_qids: list[str] = []
for item in items:
eq = self.stack.add(OpenQuestion(
text=f"What is the {attribute} of {item}?",
answer_type=AnswerType.CONSTANT,
reason=f"fan-out of {q.qid}", deps=[]))
eq.fan_group = q.qid
entity_qids.append(eq.qid)
# 2) the join: an EXISTING dependent that asks for the sum/total is
# promoted to join (deterministic sum); otherwise create one
join_q: OpenQuestion | None = None
for other in self.stack.items:
if other is q or other.status != "open" or other.parent_goal:
continue
if q.qid in other.deps and re.search(r"\b(sum|total)\b", other.text, re.I):
join_q = other
break
if join_q is None:
join_q = self.stack.add(OpenQuestion(
text=re.sub(r"\?+$", "", re.sub(self.FANOUT_MARK, "", q.text, count=1)).strip()
+ "?",
answer_type=AnswerType.FUNCTION,
reason=f"fan-out join of {q.qid}", deps=list(entity_qids)))
join_q.fan_group = q.qid
join_q.fan_join = True
join_q.fan_source = list_eid
# 3) rewire q's dependents to the entity questions (q answers nothing)
for other in self.stack.items:
if other is not q and q.qid in other.deps:
other.deps = [d for d in other.deps if d != q.qid] + entity_qids
# 4) q is answered BY the expansion
q.status = "answered"
q.reason = f"expanded (fan-out) into {len(entity_qids)} entity questions"
self.notes.append(f"{q.qid}: {q.reason}")
self.streams.output("FANOUT", f"{q.qid} -> {len(entity_qids)} entity questions "
f"+ join {join_q.qid}")
def _join_rows(self, q: OpenQuestion) -> EvidenceRow | None:
"""The join: deterministic sum over the fan group's entity rows.
Computation is its own proof (verified=True); missing values make a
PARTIAL sum, named in the note — never a silent one."""
group = q.fan_group
entity_rows = [r for r in self.table.rows()
if r.provenance.get("fan_group") == group and r.eid != q.fan_source]
nums: list[float] = []
ids: list[str] = []
for r in entity_rows:
m = re.search(r"[-+]?[\d,]*\.?\d+", str(r.payload.get("value", "")))
if m:
nums.append(float(m.group().replace(",", "")))
ids.append(r.eid)
if not nums:
return None
total = sum(nums)
partial = len(nums) < len(entity_rows)
self.streams.state(f"join: sum of {len(nums)} entity rows = {total}", think=True)
return EvidenceRow(
qid=q.qid, answer_type=AnswerType.FUNCTION,
payload={"value": _fmt_num(total), "sum_of": ids,
"sum_count": len(nums)},
engine="logic:join",
trace=[f"deterministic sum over {len(nums)} entity rows: "
f"{' + '.join(ids)}"],
provenance={"op": "sum", "operands": ids, "fan_group": group},
verified=True, # computation is its own proof
note=(f"partial: {len(nums)} of {len(entity_rows)} values summed"
if partial else ""))
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
@@ -173,6 +317,29 @@ class FloopRun:
q.status = "answered"
q.reason = "setop computed"
return
# FAN-OUT GUARD (planner): a subquestion that asks for an attribute
# 'for each' item of a list row in its deps is N entity questions +
# 1 join — never ONE knowledge question over all entities at once.
fan = self._detect_fanout(q)
if fan is not None:
self._expand_fanout(q, fan)
return
# FAN-OUT JOIN: the join question never routes anywhere — its answer
# is a deterministic sum over the fan group's entity rows
if q.fan_join and q.fan_group:
row = self._join_rows(q)
if row is not None:
self.table.append(row)
self.engine_calls += 1
self.streams.output("JOIN",
f"sum = {row.payload['value']} "
f"({row.payload['sum_count']} values) [computed]")
q.status = "answered"
q.reason = "fan-out join computed"
return
# no numeric rows yet: leave open — entity rows are still coming
self.notes.append(f"{q.qid}: join found no numeric rows yet")
return
self._charge()
self.streams.call("ROUTE", f"{q.qid}: {q.text[:80]}",
think=self.tprefix + f"routing {q.qid}: {q.text[:90]}")
@@ -246,6 +413,9 @@ class FloopRun:
def _append_checked(self, row: EvidenceRow, q: OpenQuestion) -> None:
"""STUB arrival check (design: type check + contradiction check). Only the
trivial refusal fires: an expert that reports UNKNOWN fails its question."""
# fan-out bookkeeping: entity rows carry the group so the join finds them
if q.fan_group:
row.provenance["fan_group"] = q.fan_group
self.table.append(row)
if str(row.payload.get("value", "")).strip().upper() == "UNKNOWN":
q.status = "failed"
+4
View File
@@ -35,6 +35,10 @@ class OpenQuestion:
reason: str = "" # init | missing | child-goal
qid: str = "" # assigned by QuestionStack
status: str = "open" # open | answered | failed
# fan-out bookkeeping (set by the machine's planner expansion)
fan_group: str = "" # original qid whose expansion produced this question
fan_join: bool = False # this question is the group's join (sum) question
fan_source: str = "" # the list row eid the expansion reads
@dataclass