(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).
177 lines
6.3 KiB
Python
177 lines
6.3 KiB
Python
"""Shared state: evidence table, open questions, budget. The machine's data structures.
|
|
|
|
Laws enforced here (PIPELINE.md §5):
|
|
- the table is append-only; retraction is a flag, never a deletion
|
|
- every row carries provenance and a trace
|
|
- prose is never stored: payload is a typed dict; verbatim quotes live in payload["quote"]
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
import time
|
|
from dataclasses import dataclass, field
|
|
from enum import Enum
|
|
|
|
|
|
class AnswerType(str, Enum):
|
|
OPEN = "OPEN"
|
|
FUNCTION = "FUNCTION"
|
|
INTERVAL = "INTERVAL"
|
|
CONSTANT = "CONSTANT"
|
|
LIST = "LIST"
|
|
|
|
|
|
class BudgetExhausted(Exception):
|
|
pass
|
|
|
|
|
|
@dataclass
|
|
class OpenQuestion:
|
|
text: str
|
|
answer_type: AnswerType = AnswerType.OPEN
|
|
deps: list[str] = field(default_factory=list) # qids this question waits on
|
|
parent_goal: bool = False
|
|
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
|
|
class EvidenceRow:
|
|
answer_type: AnswerType
|
|
payload: dict # typed fields; for knowledge: {"quote": ..., "url": ...} verbatim only
|
|
engine: str # e.g. "stub:knowledge", "floop-child"
|
|
eid: str = "" # assigned by EvidenceTable.append
|
|
qid: str = ""
|
|
trace: list[str] = field(default_factory=list)
|
|
provenance: dict = field(default_factory=dict) # expert, llm_calls, ts, cost
|
|
verified: bool = False
|
|
note: str = "" # type mismatches, failures — never prose claims
|
|
retracted: bool = False
|
|
|
|
|
|
class EvidenceTable:
|
|
def __init__(self) -> None:
|
|
self._rows: list[EvidenceRow] = []
|
|
self._next = 1
|
|
|
|
def append(self, row: EvidenceRow) -> EvidenceRow:
|
|
if row.payload is None or not isinstance(row.payload, dict):
|
|
raise ValueError("payload must be a typed dict — no free-form prose (table law 4)")
|
|
row.eid = f"E{self._next}"
|
|
self._next += 1
|
|
self._rows.append(row) # append-only
|
|
return row
|
|
|
|
def row(self, eid: str) -> EvidenceRow | None:
|
|
return next((r for r in self._rows if r.eid == eid), None)
|
|
|
|
def rows(self) -> list[EvidenceRow]:
|
|
return list(self._rows)
|
|
|
|
def for_question(self, qid: str) -> list[EvidenceRow]:
|
|
return [r for r in self._rows if r.qid == qid]
|
|
|
|
def dump(self) -> str:
|
|
out = []
|
|
for r in self._rows:
|
|
mark = "verified" if r.verified else "unverified"
|
|
ret = " RETRACTED" if r.retracted else ""
|
|
out.append(
|
|
f"{r.eid} (answers {r.qid}, {r.answer_type.value}, {mark}{ret}) "
|
|
f"engine={r.engine} payload={json.dumps(r.payload, ensure_ascii=False)}"
|
|
+ (f" note={r.note}" if r.note else "")
|
|
)
|
|
return "\n".join(out) if out else "(empty)"
|
|
|
|
|
|
class QuestionStack:
|
|
def __init__(self, goal: str) -> None:
|
|
self.goal = OpenQuestion(text=goal, parent_goal=True, reason="user question")
|
|
self.goal.qid = "Q0"
|
|
self.items: list[OpenQuestion] = [self.goal]
|
|
self._next = 1
|
|
|
|
def add(self, q: OpenQuestion) -> OpenQuestion:
|
|
q.qid = f"Q{self._next}"
|
|
self._next += 1
|
|
self.items.append(q)
|
|
return q
|
|
|
|
def pickable(self, table: EvidenceTable) -> OpenQuestion | None:
|
|
"""First open question whose deps are answered. Dependency order IS execution order — no search."""
|
|
failed_qids = {i.qid for i in self.items if i.status == "failed" and not i.parent_goal}
|
|
updated = True
|
|
while updated: # cascade: a failed dependency kills its dependents too
|
|
updated = False
|
|
for q in self.items:
|
|
if q.status != "open" or q.parent_goal:
|
|
continue
|
|
if table.for_question(q.qid):
|
|
continue # already has evidence — never re-picked (loop guard)
|
|
dead = [d for d in q.deps if d in failed_qids]
|
|
if dead:
|
|
q.status = "failed"
|
|
q.reason = "dependency failed: " + ",".join(dead)
|
|
failed_qids.add(q.qid)
|
|
updated = True
|
|
continue
|
|
if all(table.for_question(d) for d in q.deps):
|
|
return q
|
|
return None
|
|
|
|
def open_count(self) -> int:
|
|
return sum(1 for q in self.items if q.status == "open" and not q.parent_goal)
|
|
|
|
def all_terminal(self) -> bool:
|
|
"""Every subquestion answered or failed — the goal itself is 'answered'
|
|
by the synthesis step, not by a row (prover stub lives in the machine)."""
|
|
return all(q.status in ("answered", "failed")
|
|
for q in self.items if not q.parent_goal)
|
|
|
|
|
|
@dataclass
|
|
class Budget:
|
|
max_llm_calls: int
|
|
max_depth: int
|
|
max_retries: int
|
|
missing_extensions: int
|
|
min_child_budget: int = 6
|
|
llm_calls: int = 0
|
|
engine_calls: int = 0
|
|
missing_used: int = 0
|
|
|
|
def charge_llm(self) -> None:
|
|
if self.llm_calls >= self.max_llm_calls:
|
|
raise BudgetExhausted(f"llm_calls={self.llm_calls}/{self.max_llm_calls}")
|
|
self.llm_calls += 1
|
|
|
|
def slice_for_child(self) -> "Budget":
|
|
remaining = self.max_llm_calls - self.llm_calls
|
|
child = Budget(
|
|
max_llm_calls=max(self.min_child_budget, remaining // 2),
|
|
max_depth=self.max_depth,
|
|
max_retries=self.max_retries,
|
|
missing_extensions=self.missing_extensions,
|
|
min_child_budget=self.min_child_budget,
|
|
)
|
|
return child
|
|
|
|
|
|
def instantiate(text: str, table: EvidenceTable) -> str:
|
|
"""ReWOO plan-on-slots: replace #E<n> references with the row's value."""
|
|
def sub(m: re.Match) -> str:
|
|
r = table.row(f"E{m.group(1)}")
|
|
if r is None:
|
|
return m.group(0)
|
|
val = r.payload.get("value", r.payload.get("quote", r.payload.get("user_reply")))
|
|
if val is None:
|
|
val = json.dumps(r.payload, ensure_ascii=False)
|
|
return str(val)
|
|
|
|
return re.sub(r"#E(\d+)", sub, text) |