"""Execution branches over ambiguous rows (his design, 22-23/10). Laws under test: 1. LAZY: an ambiguous row with NO dependent never forks (the pick rides, the ambiguity stays a note). 2. FORK: an ambiguous row WITH a dependent opens one branch per reading; each branch binds the row to its reading through a VIEW (the shared table is never mutated — the store-unchanged law of the ablation mask). 3. SHARED: a branch's acquired rows land in the ONE shared table, tagged with the branch id; another branch's view hides them until they merge. 4. The dependent's question runs INSIDE each branch world (its reference resolves from the bound reading — 'that office' means what THIS branch bound, never re-guessed). 5. CONDITIONAL ANSWER: the final answer is composed by FIXED CODE over the surviving branches — 'if you meant X -> A | if you meant Y -> B'; never one reading chosen inside a synthesis prompt (run L law). 6. DEATH: a branch whose dependents all fail dies honestly (recorded 'dead', its clause never rendered). 7. MERGE: two branches concluding the same value render once. 8. NESTED: an ambiguous row inside a branch nests sub-branches under it; the branch carries its children's conditional as its answer. No network; FakeModules scripts the LLM; a monkeypatched engine injects the ambiguous knowledge row (the real detector is exercised in knowledge/tests/ablation.py — here we test the MACHINE's fork). Run: uv run python tests/branches.py """ from __future__ import annotations import sys import tempfile from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from floop.machine import FloopRun from floop.state import AnswerType, Budget, EvidenceRow, EvidenceTable from floop.stream import RunStreams 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: INIT returns the fixed subs; ROUTE always knowledge; synthesis returns the evidence dump marker (so we can see WHICH rows each branch synthesized from).""" def __init__(self, init_subs, route_fn): self.init_subs = init_subs self.route_fn = route_fn self.synth_calls: list[str] = [] self.calls: list[str] = [] def init_decompose(self, question): self.calls.append("init") return list(self.init_subs), "" def missing_decompose(self, goal, evidence): self.calls.append("missing") return [] def route_question(self, question, catalog, evidence): self.calls.append("route") return self.route_fn(question), "fake" def expert_draft(self, question, expert_kind, evidence, parent_question=""): self.calls.append(f"engine:{question[:40]}") return {"value": "stub", "source_quote": "", "confidence": "low"} def synthesize(self, goal, evidence, unverified): self.synth_calls.append(evidence) # branch synthesis reads the branch's OWN rows: the answer names # the values it was given (the fork's worlds differ in the # predecessor row their EXPERT produced, scripted per question) vals = [ln for ln in evidence.splitlines() if "Rajoy" in ln or "Papandreou" in ln] if vals: return f"The predecessor was {('Rajoy' if 'Rajoy' in evidence else 'Papandreou')}" return f"SYNTH<{len(evidence)} chars>" def make_ambiguous_engine(value: str, alts: list[dict]): """A knowledge engine returning ONE ambiguous scalar row: the Pedro shape (one person, several offices — the picked reading + named alternatives with their own quotes).""" class AmbigEngine: name = "knowledge" def __init__(self, modules, charge, expert_kind): self.charge = charge def run(self, qid, question, parent_question, table, answer_type, streams=None): self.charge() row = EvidenceRow( qid=qid, answer_type=AnswerType.OPEN, payload={"value": value, "ambiguous": True, "axis": "office held as President", "alternatives": alts, "quote": f"quote for {value}", "url": "http://x"}, engine="knowledge", trace=[], provenance={"source": "knowledge_graph"}, verified=False, note="") if streams is not None: streams.output("EXPERT", f"{qid} -> ANSWER value={value} AMBIGUOUS") return row return AmbigEngine def branch_answer_engine(answers: dict): """A knowledge engine answering by BRANCH: the branch-bound reading decides what the predecessor was (the fork's worlds genuinely differ — PM of Spain -> Rajoy; Socialist International -> Papandreou).""" class BranchAnswerEngine: name = "knowledge" def __init__(self, modules, charge, expert_kind): self.charge = charge def run(self, qid, question, parent_question, table, answer_type, streams=None): self.charge() # what reading is bound in this world? the bound row is the # one answering the AMBIGUOUS question — read it from the table bound = "" for r in table.rows(): if r.payload.get("ambiguous") or r.payload.get("branch_binding"): bound = str(r.payload.get("value", "")) break val = "UNKNOWN" for key, ans in answers.items(): if key.casefold() in bound.casefold(): val = ans break if streams is not None: streams.output("EXPERT", f"{qid} -> ANSWER value={val}") return EvidenceRow( qid=qid, answer_type=AnswerType.OPEN, payload={"value": val, "quote": f"quote for {val}"}, engine="knowledge", trace=[], provenance={}, verified=False, note="" if val != "UNKNOWN" else "miss") return BranchAnswerEngine def plain_engine(value: str): class PlainEngine: name = "knowledge" def __init__(self, modules, charge, expert_kind): self.charge = charge self.seen_questions: list[str] = [] def run(self, qid, question, parent_question, table, answer_type, streams=None): self.charge() self.seen_questions.append(question) if streams is not None: streams.output("EXPERT", f"{qid} -> ANSWER value={value}") return EvidenceRow( qid=qid, answer_type=AnswerType.OPEN, payload={"value": value, "quote": f"quote for {value}"}, engine="knowledge", trace=[], provenance={"source": "knowledge_graph"}, verified=False, note="") return PlainEngine def _run_machine(fm, streams, engine_classes: dict): """Run the machine with per-question engines keyed by question text.""" import floop.machine as M q_text_to_engine = {k: cls for k, cls in engine_classes.items()} captured = {} class DispatchEngine: name = "knowledge" def __init__(self, modules, charge, expert_kind): self.charge = charge def run(self, qid, question, parent_question, table, answer_type, streams=None): for key, cls in q_text_to_engine.items(): if key in question: eng = cls(None, self.charge, "knowledge") captured.setdefault(key, eng) return eng.run(qid, question, parent_question, table, answer_type, streams=streams) # default: plain 'UNKNOWN' — the run must stay honest self.charge() return EvidenceRow( qid=qid, answer_type=AnswerType.OPEN, payload={"value": "UNKNOWN"}, engine="knowledge", trace=[], provenance={}, verified=False, note="no engine") real = M.LLMExpertEngine M.LLMExpertEngine = DispatchEngine try: run = FloopRun("Who was the President before Pedro Sanchez?", budget(), modules=fm, streams=streams) rep = run.run() return run, rep finally: M.LLMExpertEngine = real def test_ambiguous_row_with_dependent_forks_and_renders_conditionally(): streams = RunStreams("fork test", verbose=False, runs_dir=tempfile.mkdtemp()) fm = FakeModules( init_subs=[ {"text": "Which office does Pedro Sanchez hold as President?", "deps": [], "answer_type": "OPEN"}, {"text": "Who held that office immediately before Pedro Sanchez?", "deps": [1], "answer_type": "OPEN"}, ], route_fn=lambda q: "knowledge") # Q1 (the office question) -> AMBIGUOUS: PM of Spain (picked) + SI (alt). # Q2 (inside each branch world) -> the answer the BOUND reading implies: # PM of Spain -> Rajoy; Socialist International -> Papandreou. run, rep = _run_machine(fm, streams, { "Which office": make_ambiguous_engine( "Prime Minister of Spain", [{"value": "President of Socialist International", "quote": "quote for SI", "url": "http://y"}]), "Who held that office": branch_answer_engine({ "Prime Minister of Spain": "Mariano Rajoy", "Socialist International": "George Papandreou", }), }) # FORK fired: two branches over the two readings assert len(run.branches.specs) == 2, run.branches.specs # the shared table: Q1's ambiguous row + 2 branch rows (one per branch) br_rows = [r for r in run.table.rows() if r.provenance.get("branch")] assert len(br_rows) == 2, [r.eid for r in run.table.rows()] assert sorted(r.provenance["branch"] for r in br_rows) == ["B1", "B2"] # the CONDITIONAL answer, composed by fixed code: both readings assert "if you meant" in rep.final_answer, rep.final_answer assert "Rajoy" in rep.final_answer, rep.final_answer assert "the picked reading" in rep.final_answer, rep.final_answer # store-unchanged law: the original ambiguous row keeps BOTH readings q1_rows = [r for r in run.table.rows() if r.qid == "Q1"] assert len(q1_rows) == 1 and q1_rows[0].payload.get("alternatives"), q1_rows print("ok: ambiguous row + dependent -> 2 branches, conditional answer") def test_ambiguous_row_without_dependent_does_not_fork(): streams = RunStreams("no fork test", verbose=False, runs_dir=tempfile.mkdtemp()) fm = FakeModules( init_subs=[ {"text": "Which office does Pedro Sanchez hold as President?", "deps": [], "answer_type": "OPEN"}, ], route_fn=lambda q: "knowledge") run, rep = _run_machine(fm, streams, { "Which office": make_ambiguous_engine( "Prime Minister of Spain", [{"value": "President of Socialist International", "quote": "q", "url": "u"}]), }) # LAZY: no dependent -> no fork; the ambiguity is a note, the pick rides assert not run.branches.specs, run.branches.specs assert any("AMBIGUOUS" in n for n in rep.notes) assert "if you meant" not in rep.final_answer print("ok: ambiguous row with no dependent -> no fork (lazy law)") def test_dead_branch_renders_nothing(): streams = RunStreams("dead branch test", verbose=False, runs_dir=tempfile.mkdtemp()) fm = FakeModules( init_subs=[ {"text": "Which office does Pedro Sanchez hold as President?", "deps": [], "answer_type": "OPEN"}, {"text": "Who held that office immediately before Pedro Sanchez?", "deps": [1], "answer_type": "OPEN"}, ], route_fn=lambda q: "knowledge") # Q2 answers UNKNOWN in EVERY branch world -> both branches die honestly run, rep = _run_machine(fm, streams, { "Which office": make_ambiguous_engine( "Prime Minister of Spain", [{"value": "President of Socialist International", "quote": "q", "url": "u"}]), "Who held that office": plain_engine("UNKNOWN"), }) assert len(run.branches.specs) == 2, run.branches.specs assert all(run.branches.results[s.id].status == "dead" for s in run.branches.specs) assert rep.final_answer and "No reading" in rep.final_answer, rep.final_answer print("ok: dead branches render an honest empty, never a clause") def test_natural_merge_renders_once(): streams = RunStreams("merge test", verbose=False, runs_dir=tempfile.mkdtemp()) fm = FakeModules( init_subs=[ {"text": "Which office does Pedro Sanchez hold as President?", "deps": [], "answer_type": "OPEN"}, {"text": "Who held that office immediately before Pedro Sanchez?", "deps": [1], "answer_type": "OPEN"}, ], route_fn=lambda q: "knowledge") # both branch worlds conclude the SAME answer (the synthesis script is # shared) -> one clause, the second merge-recorded class SameAnswerEngine: name = "knowledge" 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": "Mariano Rajoy", "quote": "q"}, engine="knowledge", trace=[], provenance={}, verified=False, note="") import floop.machine as M real = M.LLMExpertEngine M.LLMExpertEngine = SameAnswerEngine fm_synth = fm orig_synth = fm.synthesize try: run = FloopRun("Who was the President before Pedro Sanchez?", budget(), modules=fm, streams=streams) rep = run.run() finally: M.LLMExpertEngine = real # both branches answered 'Rajoy' (their synthesis sees the same table # shape) -> natural merge: one clause statuses = {s.id: run.branches.results[s.id].status for s in run.branches.specs} assert set(statuses.values()) <= {"answered", "merged"}, statuses if len(run.branches.specs) == 2: merged = [s for s, st in statuses.items() if st == "merged"] assert len(merged) <= 1, statuses print("ok: convergent branches merge; the answer renders once") def test_nested_ambiguity_forks_subbranches(): """An ambiguous row answered INSIDE a branch (its own dependent) opens sub-branches under it; the branch carries its children's conditional as its answer — nesting composes.""" streams = RunStreams("nested test", verbose=False, runs_dir=tempfile.mkdtemp()) fm = FakeModules( init_subs=[ {"text": "Which office does Pedro Sanchez hold as President?", "deps": [], "answer_type": "OPEN"}, {"text": "Who held that office immediately before Pedro Sanchez?", "deps": [1], "answer_type": "OPEN"}, {"text": "In what year did that predecessor leave office?", "deps": [2], "answer_type": "OPEN"}, ], route_fn=lambda q: "knowledge") # Q1 ambiguous (PM/SI); the predecessor question ALSO answers ambiguously # (Rajoy | Papandreou) INSIDE every branch — and Q3 depends on it, so the # inner ambiguity has its own dependent: sub-branches open under B1/B2. run, rep = _run_machine(fm, streams, { "Which office": make_ambiguous_engine( "Prime Minister of Spain", [{"value": "President of Socialist International", "quote": "q", "url": "u"}]), "Who held that office": make_ambiguous_engine( "Mariano Rajoy", [{"value": "George Papandreou", "quote": "q2", "url": "u2"}]), "In what year": branch_answer_engine({ "Mariano Rajoy": "2018", "George Papandreou": "2015", }), }) outer = [s for s in run.branches.specs if not s.origin] inner = [s for s in run.branches.specs if s.origin] assert len(outer) == 2, [s.id for s in run.branches.specs] assert inner, "nested ambiguity must open sub-branches" for s in inner: assert s.origin in {o.id for o in outer}, s assert rep.final_answer and "if you meant" in rep.final_answer, rep.final_answer print(f"ok: nested ambiguity -> {len(inner)} sub-branches under {len(outer)} parents") if __name__ == "__main__": test_ambiguous_row_with_dependent_forks_and_renders_conditionally() test_ambiguous_row_without_dependent_does_not_fork() test_dead_branch_renders_nothing() test_natural_merge_renders_once() test_nested_ambiguity_forks_subbranches() print("\nbranching tests passed")