floop v0.1: design docs + executable dspy draft
Root: README, PIPELINE, ALGORITHM, GAPS, RUNLOG (design + first executable runs). code/: v0.1 draft on dspy 3.4 (INIT/ROUTE/EXPERT/MISSING/ANSWER as dspy calls, machine as fixed code, stub engines — honest Unverified). knowledge/: DESIGN.md for the KG-first knowledge expert (pre-implementation).
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
"""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)
|
||||
|
||||
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
|
||||
|
||||
|
||||
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")
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Unit tests for the machine's fixed code — no LLM needed. Run:
|
||||
|
||||
.venv/bin/python -m pytest tests/ -q (or) .venv/bin/python tests/state.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from floop.dspy_modules import parse_subquestions
|
||||
from floop.state import (AnswerType, Budget, BudgetExhausted, EvidenceRow,
|
||||
EvidenceTable, OpenQuestion, QuestionStack, instantiate)
|
||||
|
||||
|
||||
def test_table_append_only_and_typed():
|
||||
t = EvidenceTable()
|
||||
t.append(EvidenceRow(qid="Q1", answer_type=AnswerType.OPEN,
|
||||
payload={"value": "4"}, engine="stub:numeric", verified=False))
|
||||
assert t.rows()[0].eid == "E1"
|
||||
try:
|
||||
t.append(EvidenceRow(qid="Q2", answer_type=AnswerType.OPEN,
|
||||
payload="prose!", engine="x")) # type: ignore[arg-type]
|
||||
raise AssertionError("prose payload must be refused")
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
|
||||
def test_pickable_dependency_order():
|
||||
t = EvidenceTable()
|
||||
s = QuestionStack("goal?")
|
||||
a = s.add(OpenQuestion(text="a?"))
|
||||
b = s.add(OpenQuestion(text="b?", deps=[a.qid]))
|
||||
assert s.pickable(t) is a # b waits although it is first in line? no: a first
|
||||
t.append(EvidenceRow(qid=a.qid, answer_type=AnswerType.OPEN,
|
||||
payload={"value": "va"}, engine="stub"))
|
||||
assert s.pickable(t) is b
|
||||
|
||||
|
||||
def test_failed_dependency_cascade():
|
||||
t = EvidenceTable()
|
||||
s = QuestionStack("goal?")
|
||||
a = s.add(OpenQuestion(text="a?", status="failed"))
|
||||
b = s.add(OpenQuestion(text="b?", deps=[a.qid]))
|
||||
c = s.add(OpenQuestion(text="c?", deps=[b.qid]))
|
||||
assert s.pickable(t) is None
|
||||
assert b.status == "failed" and c.status == "failed"
|
||||
assert s.all_terminal()
|
||||
|
||||
|
||||
def test_unknown_deps_never_pick():
|
||||
t = EvidenceTable()
|
||||
s = QuestionStack("goal?")
|
||||
b = s.add(OpenQuestion(text="b?", deps=["Q7"])) # Q7 does not exist
|
||||
assert s.pickable(t) is None # waits forever: a dep with no row is not answered
|
||||
|
||||
|
||||
def test_budget_charge():
|
||||
b = Budget(max_llm_calls=2, max_depth=2, max_retries=3, missing_extensions=1)
|
||||
b.charge_llm(); b.charge_llm()
|
||||
try:
|
||||
b.charge_llm()
|
||||
raise AssertionError("budget must refuse the 3rd call")
|
||||
except BudgetExhausted:
|
||||
pass
|
||||
|
||||
|
||||
def test_instantiate_slots():
|
||||
t = EvidenceTable()
|
||||
t.append(EvidenceRow(qid="Q1", answer_type=AnswerType.CONSTANT,
|
||||
payload={"value": "Grover's algorithm"}, engine="stub"))
|
||||
out = instantiate("which algorithm: #E1?", t)
|
||||
assert out == "which algorithm: Grover's algorithm?"
|
||||
|
||||
|
||||
def test_parse_subquestions_forms():
|
||||
subs = parse_subquestions(
|
||||
"1. How many qubits are needed? | none | FUNCTION\n"
|
||||
"2. What is the clock speed? | 1 | INTERVAL\n")
|
||||
assert subs[0]["text"].endswith("needed?") and subs[0]["deps"] == []
|
||||
assert subs[1]["deps"] == [1] and subs[1]["answer_type"] == AnswerType.INTERVAL
|
||||
|
||||
|
||||
def test_parse_refs_and_garbage():
|
||||
subs = parse_subquestions("depends on #E2 | #E2 | OPEN\nnot a subquestion line")
|
||||
assert subs and subs[0]["deps"] == ["#E2"]
|
||||
assert parse_subquestions("") == []
|
||||
assert parse_subquestions("|||") == []
|
||||
|
||||
|
||||
def test_child_budget_slice():
|
||||
b = Budget(max_llm_calls=20, max_depth=2, max_retries=3, missing_extensions=1)
|
||||
b.llm_calls = 4
|
||||
child = b.slice_for_child()
|
||||
assert 6 <= child.max_llm_calls <= 16
|
||||
|
||||
|
||||
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)} tests passed")
|
||||
Reference in New Issue
Block a user