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:
+2
-1
@@ -16,7 +16,8 @@ lm:
|
||||
api_key_env: OLLAMA_API_KEY
|
||||
|
||||
budget:
|
||||
max_llm_calls: 40 # per FLOOP run (children get a slice)
|
||||
max_llm_calls: 80 # per FLOOP run (children get a slice; fan-outs multiply
|
||||
# entity questions — a 3-river fan needs ~3x a scalar)
|
||||
min_child_budget: 6
|
||||
max_depth: 2 # recursion cap (PIPELINE.md §8.4)
|
||||
max_retries: 3 # bounded self-refinement on unparseable LLM output
|
||||
|
||||
+172
-2
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -230,11 +230,12 @@ class KnowledgeExpert:
|
||||
# rows and answer by aggregation (no extract calls, no gate)
|
||||
if list_mode and page.tables:
|
||||
ans = self._list_from_page(page, question, charge_llm)
|
||||
if ans is not None:
|
||||
if ans is not None and self._guard_ingest(ans, evidence):
|
||||
self._log(f"early exit after {page.title}: list "
|
||||
f"({ans['list_count']} items)", think=True)
|
||||
return {**ans, "source": "knowledge_graph",
|
||||
"stats": {"pages": [p.title for p in pages]}}
|
||||
# refused by the guard: wrong article's list — keep gathering
|
||||
# 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). For enumerations the set gate applies
|
||||
@@ -268,6 +269,57 @@ class KnowledgeExpert:
|
||||
"pages": [p.title for p in pages],
|
||||
"elapsed_s": round(time.time() - t0, 1)}}
|
||||
|
||||
def _expected_entities(self, evidence: str) -> list[str]:
|
||||
"""Entities the parent's evidence already names — 'the three longest
|
||||
rivers' means the answer's members must be among them. Extracted
|
||||
deterministically from the rendered evidence lines (E1: value (answers
|
||||
Qx)), from LIST rows' list_items and scalar rows' values. No LLM."""
|
||||
out: list[str] = []
|
||||
for line in (evidence or "").splitlines():
|
||||
if "(answers" not in line:
|
||||
continue
|
||||
val = line.split(":", 1)[1].split("(answers")[0].strip()
|
||||
if not val:
|
||||
continue
|
||||
# LIST rows render 'list of N items: a, b, c...' — members are known
|
||||
m = re.match(r"list of \d+ items: (.+)$", val)
|
||||
if m:
|
||||
out.extend(t.strip() for t in m.group(1).rstrip(".").split(","))
|
||||
continue
|
||||
# scalar: a single named entity (Po) or a short comma list (Po, Adige, Tiber)
|
||||
if len(val.split()) <= 6 and not val.isdigit():
|
||||
out.extend(t.strip() for t in val.split(",") if t.strip())
|
||||
return [e for e in out if e]
|
||||
|
||||
def _disjoint(self, members: list[str], expected: list[str]) -> bool:
|
||||
"""Deterministic overlap check, case-insensitive by prefix-normalized
|
||||
tokens. Disjoint (or near-disjoint) ingest is WRONG for a question
|
||||
about known entities — keep gathering, don't answer from it."""
|
||||
if not expected or not members:
|
||||
return False
|
||||
en = {norm_name(e) for e in expected}
|
||||
mn = {norm_name(m) for m in members}
|
||||
inter = en & mn
|
||||
# no expected entity appears, or < 1/3 do: wrong article's list
|
||||
return len(inter) * 3 < len(mn) or not inter
|
||||
|
||||
def _guard_ingest(self, ans: dict, evidence: str) -> bool:
|
||||
"""The disjointness guard: refuse a LIST ingest whose members don't
|
||||
overlap the entities the parent's evidence already names. 'Cabal de
|
||||
Po, Adige, Tiber' must never be answered by the Amazon's flow."""
|
||||
if not (evidence and ans.get("list_items")):
|
||||
return True # nothing to check against — ingest is fine
|
||||
expected = self._expected_entities(evidence)
|
||||
if not expected:
|
||||
return True
|
||||
if self._disjoint(ans["list_items"], expected):
|
||||
self._log(
|
||||
f"guard: ingest of {len(ans['list_items'])} members disjoint from "
|
||||
f"{len(expected)} expected entities — refusing, gather continues",
|
||||
think=True)
|
||||
return False
|
||||
return True
|
||||
|
||||
def _is_enumeration(self, question: str) -> bool:
|
||||
"""Deterministic LIST detection: plural nouns + enumeration ask words.
|
||||
Cheap, logged, and overridable by the planner's explicit answer_type."""
|
||||
@@ -370,7 +422,10 @@ class KnowledgeExpert:
|
||||
self._merged += 1
|
||||
if not members:
|
||||
return None
|
||||
items = sorted(set(members))
|
||||
# ORDER-PRESERVING dedup: the table's order IS information (a ranked
|
||||
# table ranks — top-N slices read it). Sorting alphabetically imposed
|
||||
# an order the source never had.
|
||||
items = list(dict.fromkeys(members))
|
||||
self._log(f"LIST ingest: {len(items)} members of '{set_name}' from "
|
||||
f"table {idx} ({table.total_rows} rows)", think=True)
|
||||
# ANSWER-LEVEL CHECK: corroborate the count from prose OUTSIDE the
|
||||
|
||||
@@ -296,6 +296,34 @@ def test_list_ingest_aggregate(tmp="/tmp/floop_kg_list.sqlite"):
|
||||
print("ok test_list_ingest_aggregate")
|
||||
|
||||
|
||||
def test_disjoint_guard_refuses_wrong_list():
|
||||
"""The disjointness guard: an ingest whose members don't overlap the
|
||||
entities the parent's evidence names is refused; the gather continues.
|
||||
Emili's run-08: 'flow of Po, Adige, Tiber' must never be answered by the
|
||||
Amazon's flow from a world-wide discharge table."""
|
||||
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
|
||||
|
||||
ke = KnowledgeExpert.__new__(KnowledgeExpert)
|
||||
ke.cfg = KnowledgeConfig()
|
||||
ke.streams = None
|
||||
ke._log = lambda text, think=False: None
|
||||
|
||||
# the parent's evidence: a scalar row naming the three rivers
|
||||
evidence = "E1: Po, Adige, Tiber (answers Q1)"
|
||||
assert ke._expected_entities(evidence) == ["Po", "Adige", "Tiber"]
|
||||
|
||||
# a world-wide discharge list: disjoint from the expected entities
|
||||
assert ke._guard_ingest({"list_items": ["Amazon", "Congo", "Yangtze"]}, evidence) is False
|
||||
# the right list: overlap — ingest is fine
|
||||
assert ke._guard_ingest({"list_items": ["Po", "Adige", "Tiber"]}, evidence) is True
|
||||
# no evidence (top-level question): guard passes, ingest is fine
|
||||
assert ke._guard_ingest({"list_items": ["Amazon", "Congo"]}, "") is True
|
||||
# LIST row evidence: 'list of 22 items: Po, Adige, ...' also seeds entities
|
||||
ev2 = "E1: list of 3 items: Po, Adige, Tiber (answers Q1)"
|
||||
assert ke._expected_entities(ev2) == ["Po", "Adige", "Tiber"]
|
||||
print("ok test_disjoint_guard_refuses_wrong_list")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_chunker_sections()
|
||||
test_containment()
|
||||
@@ -304,4 +332,5 @@ if __name__ == "__main__":
|
||||
test_verify_count()
|
||||
test_list_ingest_aggregate()
|
||||
test_table_parser_untruncated()
|
||||
print(f"\n{test_table_parser_untruncated.__name__} etc — 7 knowledge tests passed")
|
||||
test_disjoint_guard_refuses_wrong_list()
|
||||
print(f"\n{test_table_parser_untruncated.__name__} etc — 8 knowledge tests passed")
|
||||
@@ -129,6 +129,110 @@ def test_lm_death_aborts_cleanly():
|
||||
assert rep.notes, "notes must explain the abort"
|
||||
|
||||
|
||||
def test_fanout_expansion_and_join():
|
||||
"""The planner's fan-out: 'for each' over a list row becomes N entity
|
||||
questions + one join; the join sums the entity rows deterministically.
|
||||
Emili's run-08 case: flows of the three longest rivers of Italy."""
|
||||
import floop.machine as M
|
||||
from floop.state import AnswerType as AT, EvidenceRow
|
||||
|
||||
class FlowEngine:
|
||||
"""LIST questions get the 3-river ranked list; CONSTANT questions
|
||||
answer 1540 m3/s (every river); other kinds pass through."""
|
||||
def __init__(self, modules, charge, expert_kind):
|
||||
self.charge = charge
|
||||
def run(self, qid, question, parent_question, table, answer_type, streams=None):
|
||||
if answer_type == AT.LIST:
|
||||
payload = {"value": "3",
|
||||
"list_items": ["Po", "Adige", "Tiber"], "list_count": 3}
|
||||
else:
|
||||
payload = {"value": "1540 m3/s"}
|
||||
row = EvidenceRow(qid=qid, answer_type=answer_type, payload=payload,
|
||||
engine="stub", trace=[], provenance={}, verified=False, note="")
|
||||
if streams is not None:
|
||||
streams.output("EXPERT", f"value={payload['value']}")
|
||||
return row
|
||||
|
||||
M.LLMExpertEngine = FlowEngine
|
||||
try:
|
||||
fm = FakeModules(
|
||||
init_subs=[
|
||||
{"text": "What are the three longest rivers in Italy?",
|
||||
"deps": [], "answer_type": "LIST"},
|
||||
{"text": "What is the average annual water flow (discharge) "
|
||||
"for each of those three rivers?",
|
||||
"deps": [1], "answer_type": "CONSTANT"},
|
||||
{"text": "What is the sum of the water flows of the three rivers?",
|
||||
"deps": [2], "answer_type": "FUNCTION"},
|
||||
],
|
||||
route_fn=lambda q: "numeric",
|
||||
expert_value="1540")
|
||||
run = FloopRun("total flow of the three longest rivers of Italy?",
|
||||
budget(), modules=fm)
|
||||
rep = run.run()
|
||||
# the fan-out fired: 3 entity questions, one per river
|
||||
entity_qs = [q for q in run.stack.items if q.reason.startswith("fan-out of")]
|
||||
assert len(entity_qs) == 3, [q.text for q in run.stack.items]
|
||||
texts = {q.text for q in entity_qs}
|
||||
assert any("Po" in t for t in texts) and any("Tiber" in t for t in texts)
|
||||
# the join computed a deterministic sum: 3 x 1540 = 4620
|
||||
join_rows = [e for e in rep.evidence_rows if "logic:join" in e]
|
||||
assert join_rows and '"value": "4620"' in join_rows[0], join_rows
|
||||
# the 'for each' question is answered by the expansion, not an engine
|
||||
q2 = run.stack.items[2]
|
||||
assert q2.status == "answered" and "expanded" in q2.reason
|
||||
finally:
|
||||
M.LLMExpertEngine = _restore_llm_engine
|
||||
print("ok test_fanout_expansion_and_join")
|
||||
|
||||
|
||||
def test_fanout_respects_top_n_slice():
|
||||
"""'for each of those three rivers' over a 5-row list means top 3 by
|
||||
table order — never 5 entity questions."""
|
||||
fm = FakeModules(
|
||||
init_subs=[
|
||||
{"text": "What are the longest rivers in Italy?",
|
||||
"deps": [], "answer_type": "LIST"},
|
||||
{"text": "What is the flow for each of those three rivers?",
|
||||
"deps": [1], "answer_type": "CONSTANT"},
|
||||
],
|
||||
route_fn=lambda q: "knowledge",
|
||||
expert_value="100")
|
||||
# fake the LIST row: run's table gets a 5-item list answer for Q1
|
||||
run = FloopRun("goal?", budget(), modules=fm)
|
||||
# script Q1's answer: a route to knowledge; we inject the row manually by
|
||||
# patching the engine call — simpler: pre-build the list row via the
|
||||
# setop-free path: monkeypatch LLMExpertEngine.run to return a list row
|
||||
import floop.machine as M
|
||||
|
||||
class ListRowEngine:
|
||||
def __init__(self, modules, charge, expert_kind):
|
||||
self.charge = charge
|
||||
def run(self, qid, question, parent_question, table, answer_type, streams=None):
|
||||
from floop.state import AnswerType as AT, EvidenceRow
|
||||
row = EvidenceRow(
|
||||
qid=qid, answer_type=AT.LIST,
|
||||
payload={"value": "5", "list_items": ["Po", "Adige", "Tiber", "Reno", "Piave"],
|
||||
"list_count": 5},
|
||||
engine="knowledge", trace=[], provenance={}, verified=False, note="")
|
||||
if streams is not None:
|
||||
streams.output("EXPERT", "value=5 (list, 5 items)")
|
||||
return row
|
||||
|
||||
M.LLMExpertEngine = ListRowEngine
|
||||
try:
|
||||
rep = run.run()
|
||||
entity_qs = [q for q in run.stack.items if q.reason.startswith("fan-out of")]
|
||||
assert len(entity_qs) == 3, [q.text for q in run.stack.items]
|
||||
assert any("top 3" in n for n in rep.notes), rep.notes
|
||||
finally:
|
||||
M.LLMExpertEngine = _restore_llm_engine
|
||||
|
||||
|
||||
# keep a handle to restore the real engine after monkeypatching
|
||||
from floop.engine import LLMExpertEngine as _restore_llm_engine
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
|
||||
for fn in fns:
|
||||
|
||||
Reference in New Issue
Block a user