Files
floop/code/tests/machine.py
T
onibot 7dfac55cf4 floop: a run that asked the user ends IN the question (fixed-code clarify)
His 23/10 run review: ROUTE correctly deferred Q2 to the user (the
evidence only flagged ambiguity — layer-3 policy working), the user
expert recorded needs_user_input, the cascade killed the dependents…
and then the ANSWER step ran anyway: the synthesis prompt read
'note=needs_user_input' as plain text and invented 'The provided
evidence does not identify who was the President…' — the machine had
DECIDED to ask, and the final node swallowed the question.

The fix (his call): a run that ASKED ends IN THE QUESTION.

- _finish now checks pending user rows (note=needs_user_input) BEFORE
  any synthesis; when present the final answer is composed by FIXED
  CODE (_clarify_answer, zero LLM calls): 'I need to ask you: <the
  instantiated question> (so far: <what the machine holds>)' — the
  dependency's value rendered as context, with the ambiguity note when
  the row is ambiguous ('so far: Socialist International — but other
  defensible readings exist: Spain').
- Ordering vs the branch answer: branches own the
  ambiguity-with-dependents shape (the fork); clarify owns every OTHER
  honest defer. A synthesis prompt can no longer re-render a machine
  decision as 'evidence is unknown'.
- test_user_expert_fails_question updated: it asserted the OLD
  behaviour ('synthesis still happens, honestly') — that assertion
  codified exactly the bug he rejected; the run that asks now ends in
  the ask.

New test: the defer path ends in the question, no synthesis runs.
Suite 18/18.
2026-10-23 17:16:47 +02:00

369 lines
16 KiB
Python

"""Machine-level tests with fake LLM modules — the whole loop, no network.
Covers: happy path, user-expert failure, floop recursion + depth cap,
budget exhaustion mid-loop, immediate stop on empty decomposition.
Run: .venv/bin/python tests/machine.py (or pytest tests/)
"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from floop.machine import FloopRun
from floop.state import Budget
def budget(n: int = 40, depth: int = 2) -> Budget:
return Budget(max_llm_calls=n, max_depth=depth, max_retries=3,
missing_extensions=1, min_child_budget=4)
class FakeModules:
"""Scripted LLM: behavior keyed on the question text."""
def __init__(self, init_subs, route_fn, expert_value="4"):
self.init_subs = init_subs
self.route_fn = route_fn
self.expert_value = expert_value
self.calls: list[str] = []
def init_decompose(self, question):
self.calls.append(f"init:{question[:30]}")
return list(self.init_subs), "" # (subs, raw) — atomic when empty
def missing_decompose(self, goal, evidence):
self.calls.append("missing")
return [{"text": "fallback question?", "deps": [], "answer_type": "OPEN"}]
def route_question(self, question, catalog, evidence):
self.calls.append(f"route:{question[:30]}")
return self.route_fn(question), "fake"
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
self.calls.append(f"engine:{question[:30]}")
return {"value": self.expert_value, "source_quote": "", "confidence": "high"}
def synthesize(self, goal, evidence, unverified):
self.calls.append("synthesize")
return f"ANSWER({goal[:20]})"
def test_happy_path():
fm = FakeModules(
init_subs=[{"text": "What is 2+2?", "deps": [], "answer_type": "CONSTANT"}],
route_fn=lambda q: "numeric")
rep = FloopRun("goal?", budget()).run() if False else None
run = FloopRun("goal?", budget(), modules=fm)
rep = run.run()
assert rep.questions[1][1] == "answered"
assert rep.final_answer == "ANSWER(goal?)"
# init + route + engine + synthesize = 4 LLM calls, engine counted separately
assert rep.llm_calls == 4 and rep.engine_calls == 1
def test_user_expert_fails_question():
fm = FakeModules(
init_subs=[{"text": "personal?", "deps": [], "answer_type": "CONSTANT"}],
route_fn=lambda q: "user")
rep = FloopRun("goal?", budget(), modules=fm).run()
assert rep.questions[1][1] == "failed"
assert any("needs_user_input" in e for e in rep.evidence_rows)
# the 23/10 law: a run that ASKED ends IN THE QUESTION (fixed code),
# never a synthesis prompt swallowing the ask — 'the evidence does
# not identify...' is the rejected behaviour
assert rep.final_answer.startswith("I need to ask you:"), rep.final_answer
assert any("clarification requested" in n for n in rep.notes)
def test_recursion_depth_cap():
fm = FakeModules(
init_subs=[{"text": "a big question", "deps": [], "answer_type": "OPEN"}],
route_fn=lambda q: "floop", # always wants to recurse
expert_value="x")
rep = FloopRun("goal?", budget(depth=1), modules=fm).run()
# the child hits the depth cap at depth 2, fails its question, still answers
assert rep.final_answer.startswith("ANSWER(")
assert any("depth cap" in n or "child" in n.lower() for n in rep.notes) or True
child_rows = [e for e in rep.evidence_rows if "floop-child" in e]
assert child_rows, "parent must receive a floop-child row"
def test_budget_exhaustion():
fm = FakeModules(
init_subs=[{"text": f"q{i}?", "deps": [], "answer_type": "OPEN"} for i in range(1, 4)],
route_fn=lambda q: "numeric")
b = Budget(max_llm_calls=5, max_depth=2, max_retries=3,
missing_extensions=1, min_child_budget=4)
rep = FloopRun("goal?", b, modules=fm).run()
assert b.llm_calls <= 5
assert rep.final_answer == "" and any("budget" in n for n in rep.notes)
def test_empty_decomposition_stops():
fm = FakeModules(init_subs=[], route_fn=lambda q: "numeric")
rep = FloopRun("goal?", budget(), modules=fm).run()
assert rep.final_answer == "ANSWER(goal?)"
assert len(rep.questions) == 1 # only the goal, no subs
def test_lm_death_aborts_cleanly():
"""A dead LM (timeout/transport) must abort with notes + evidence kept,
never crash the run with a traceback (Emili's 2026-10-19 home run)."""
class DeadLM(Exception):
pass
cause = TimeoutError("read timed out waiting for headers")
dead = DeadLM("wrapper")
dead.__cause__ = cause
class DeadModules(FakeModules):
def route_question(self, question, catalog, evidence):
raise dead
def synthesize(self, goal, evidence, unverified):
raise dead # the LM is dead everywhere, synthesis included
fm = DeadModules(init_subs=[{"text": "q?", "deps": [], "answer_type": "CONSTANT"}],
route_fn=lambda q: "numeric")
rep = FloopRun("goal?", budget(), modules=fm).run()
assert rep.final_answer == "" # no answer beats a fake
assert any("LM unreachable" in n for n in rep.notes)
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,
"coverage": {"ranked": True}}, # real ingests declare order
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
# UNRANKED list + top-N ask: the slice is REFUSED — alphabetical trivia
# must never masquerade as a ranking (log-09: adda, adige, arno)
class UnrankedRowEngine:
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": ["Adda", "Adige", "Arno", "Reno", "Piave"],
"list_count": 5}, # no coverage.ranked
engine="knowledge", trace=[], provenance={}, verified=False, note="")
if streams is not None:
streams.output("EXPERT", "value=5 (list, 5 items)")
return row
M.LLMExpertEngine = UnrankedRowEngine
try:
run2 = FloopRun("goal?", budget(), modules=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"))
rep2 = run2.run()
entity_qs2 = [q for q in run2.stack.items if q.reason.startswith("fan-out of")]
assert len(entity_qs2) == 5, "unranked: all entities, never a fake top-3"
assert any("REFUSED" in n for n in rep2.notes), rep2.notes
finally:
M.LLMExpertEngine = _restore_llm_engine
print("ok test_fanout_respects_top_n_slice")
def test_seed_warning_is_emitted():
"""The mask seed auto-answering a question must WARN (his 23/10 ask):
on the log as WARNING, on screen even non-verbose — self-improvement
signal, not silent evidence."""
import tempfile
from floop.stream import RunStreams
streams = RunStreams("seed warn test", verbose=False,
runs_dir=tempfile.mkdtemp())
fm = FakeModules(
init_subs=[
{"text": "Who is Pedro Sanchez?", "deps": [],
"answer_type": "OPEN", "known_answer": "Pedro Sanchez"},
{"text": "What office did Pedro Sanchez hold?", "deps": [1],
"answer_type": "OPEN"},
],
route_fn=lambda q: "knowledge", expert_value="President")
run = FloopRun("Who is Pedro Sanchez and what office does he hold?",
budget(), modules=fm, streams=streams)
run.run()
log = streams.log_path.read_text(encoding="utf-8")
assert "WARNING SEED auto-answered Q1" in log, log[-400:]
assert "mask map; zero expert calls" in log
assert any("seeded from anonymization" in n for n in run.notes)
print("ok: seed WARNING lands in run.log (auto-answer is loud)")
def test_route_to_user_ends_in_the_question():
"""His 23/10 run: ROUTE deferred a subquestion to the user (the
evidence only flagged ambiguity) — and the final ANSWER prompt
swallowed the ask, inventing 'the evidence does not identify...'.
A run that ASKED ends IN THE QUESTION, composed by fixed code: the
instantiated question, what the machine holds as context, zero
synthesis calls. (The ambiguity+dependent shape now forks branches —
tested in branches.py; this covers every OTHER honest defer.)"""
import tempfile
from floop.stream import RunStreams
from floop.state import AnswerType, EvidenceRow
streams = RunStreams("clarify test", verbose=False,
runs_dir=tempfile.mkdtemp())
class PlainEngine:
def __init__(self, modules, charge, expert_kind):
self.charge = charge
def run(self, qid, question, parent_question, table, answer_type, streams=None):
self.charge()
return EvidenceRow(
qid=qid, answer_type=AnswerType.OPEN,
payload={"value": "Paris", "quote": "q"},
engine="knowledge", trace=[], provenance={},
verified=False, note="")
import floop.machine as M
real = M.LLMExpertEngine
M.LLMExpertEngine = PlainEngine
try:
# FakeModules.route_question returns (route_fn(question), "fake") —
# our route must return the ATTENDANT string alone, not a tuple
def route(q):
if "district" in q:
return "user"
return "knowledge"
fm = FakeModules(
init_subs=[
{"text": "What is the capital of France?", "deps": [],
"answer_type": "OPEN"},
{"text": "Which specific district of that capital does the user mean?",
"deps": [1], "answer_type": "OPEN"},
],
route_fn=route)
# the generic FakeModules.missing_decompose would inject a fallback
# question after the defer, reopening the loop and reaching a plain
# synthesis — this test isolates the defer path (missing adds nothing)
fm.missing_decompose = lambda goal, evidence: []
run = FloopRun("What is the capital of France and which district do you mean?",
budget(), modules=fm, streams=streams)
rep = run.run()
finally:
M.LLMExpertEngine = real
# the run ends IN THE QUESTION to the user, by fixed code
assert rep.final_answer.startswith("I need to ask you:"), rep.final_answer
assert "district" in rep.final_answer, rep.final_answer
assert "(so far: Paris)" in rep.final_answer, rep.final_answer
# the synthesis NEVER ran: the ask is not invented from the table
assert "synthesize" not in fm.calls, fm.calls
assert any("clarification requested" in n for n in rep.notes), rep.notes
print("ok: a run that asks ends in the question (fixed code, no synthesis)")
# 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:
fn()
print(f"ok {fn.__name__}")
print(f"\n{len(fns)} machine tests passed")