His 23/10 review of the merged run found Q1's answer missing from the
stream. Chain, verified against the real code:
1. Q1 ('...does the title "President" refer to in relation to
PERSON_1?') fired the mask-seed detector's loose mechanism clause —
any 'refer to' in the sentence, even when the verb governs the
TITLE, not the placeholder. The seed answered 'Pedro Sanchez' to a
question that asked which OFFICE 'President' means: wrong semantics,
a false positive born from the collision of the detector's word
list with INIT's new hidden-precondition phrasing.
Fixes (both his ask):
- identity_answer STRICT: the mechanism clause now fires only with the
placeholder as the REFERENT of 'refer(s) to' (regex adjacency, both
orders). The literal 'who/what is <ph>' clause is unchanged.
- Found while verifying: the literal clause's lookahead accepted
apostrophes, so 'Who is PERSON_1's predecessor?' (possessive) seeded
too — the old test only covered 'Who WAS...'. Apostrophe removed from
the end-of-question char class; possessives never seed again.
- THE SEED IS NOW LOUD: RunStreams.warn() (new channel — WARNING line
in run.log, [W] on screen ALWAYS, even non-verbose) fires on every
seeded answer: 'WARNING SEED auto-answered Q1 ... (mask map; zero
expert calls)'. Self-improvement signal (META): which phrasings the
seed eats belongs to the lessons bank, and it must be legible that
the machine auto-answered without any expert.
Also: ARCHITECTURE.md §9-bis — OpenTelemetry observability roadmap
(his future plan ask): run = trace, calls/steps/rows = spans carrying
today's log fields, events.jsonl as the shared bus, warnings as
first-class span events; deferred until the loop hardening settles.
Tests: anonymize +4 assertions (his false positive, possessive trap,
strict positive shapes), machine +1 (seed WARNING lands in run.log).
Suite 17/17.
302 lines
13 KiB
Python
302 lines
13 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")
|
|
|
|
|
|
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)")
|
|
|
|
|
|
# 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") |