Files
floop/code/tests/machine.py
T
onibot b5a9403063 machine: robust INIT parsing + raw-response log (run I fixes)
Run I ('Who was the President before Pedro Sanchez?'): the INIT LM wrote
its own line numbers as an extra first pipe field ('1 | Who was... |
none | OPEN'), the naive parse took '1' as the subquestion text, ROUTE
classified Q1='1' as numeric, and the machine burned four calls on
garbage before luck produced the answer. Two of the fixes close the same
observability gap that hid the root cause for a day.

1. PARSER (parse_subquestions): shifts the numbered form (>=4 fields
   with a bare number first) and drops any text that is a bare number —
   a routable question is text, never '1'. Enumerator prefixes ('1.')
   inside the text field are stripped. Well-formed lines parse exactly
   as before (regression-tested).

2. INIT DEGRADE (machine): init_decompose now returns (subs, raw).
   Non-empty raw that parses to nothing = model garbage — degrade to
   the ORIGINAL question as one OPEN subquestion (routable, logged,
   budget-safe). Empty raw keeps the old law: the question is atomic,
   stop and synthesize — never fabricate a subquestion.

3. RAW RESPONSE LOG (the ask behind the ask): prompts/NN-stage.txt now
   carries the exact LM response after the prompt. Run I's parsed
   'OUTPUT INIT: 1\n2' could not show what the model actually wrote —
   the raw text is in the file from now on; the log stays line-based.

Tests: tests/robust_init.py — the numbered form, bare-number drop,
enumerator strip, happy-path regression, the degrade, the atomic stop,
raw-response capture. Suite 59/59. Smoke: the exact run-I transcript
replayed through the real machine (DummyLM) parses to Q1/Q2 real
subquestions and answers Mariano Rajoy.
2026-10-21 12:08:50 +02:00

276 lines
12 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)
assert rep.final_answer == "ANSWER(goal?)" # synthesis still happens, honestly
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")
# 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")