Merge pull request 'Execution branches over ambiguity: fork per reading, conditional answer' (#21) from feature/branching-fork into main

This commit was merged in pull request #21.
This commit is contained in:
2026-10-23 16:29:44 +02:00
5 changed files with 916 additions and 14 deletions
+34
View File
@@ -136,6 +136,40 @@ them) are dimensions of the answer function, never branches. And one thing can n
retracted: the user. A user-supplied fact colliding with a source is presented verbatim
to the user — never silently resolved.
## 6-bis. Execution branches over ambiguity (2026-10-23, coded)
When an expert answers with SEVERAL defensible readings (the knowledge ablation audit
flags `ambiguous` + named alternatives), a question that DEPENDS on that row does not
inherit the coin-flip. The machine opens ONE EXECUTION BRANCH PER READING:
- **Lazy.** The branch is born only when the ambiguous row has an open dependent
subtree — an ambiguity nobody downstream needs stays a note; the picked reading rides.
The subtree is frozen at fork time: every branch of the fork copies the same questions.
- **A branch is a world, not a fork of the run.** The branch reads the shared evidence
table through a VIEW that binds the ambiguous row to its reading (the same law as the
ablation mask: the table is never mutated — the original row keeps all its readings)
and hides other branches' rows. Acquired knowledge (new rows, KG facts, fetched
articles, conclusions) lands in the ONE shared store, tagged with the branch id —
a later branch reuses an earlier branch's gathering for free.
- **Death is honest.** A branch dies by contradiction, dead end (all its questions
failed — UNKNOWN), or natural merge (its answer equals another branch's — deduped by
normalized value, one conclusion). Never by an absurdity judge: surprising-but-cited
answers render.
- **Nesting composes.** An ambiguous row answered INSIDE a branch (with its own
dependent) opens sub-branches under it, under the same branch cap; a parent carries
its children's conditional as its answer.
- **The final answer is conditional, composed by fixed code** — `if you meant the
PM-of-Spain reading -> Rajoy | if you meant Socialist International -> Papandreou`.
Never one reading chosen inside a synthesis prompt; never the alternatives handed to
the next question's context (that only moves the coin-flip into answer_kg).
- Clarifying with the user instead of running the branches is a POLICY ABOVE this
mechanism (layer 3): asking = picking one branch upstairs. The mechanism itself
always runs the worlds it needs.
Budget: branches share the run's `llm_calls` pool (a fork of N readings costs ~N× the
dependent subtree — leave headroom or the later branches die by budget, honestly noted);
branch count is capped (extra readings are dropped and NAMED, never silent).
## 7. Per-call context composition
Every LLM call gets its own purpose-built context, assembled by fixed code within the
+1
View File
@@ -50,6 +50,7 @@ Compare: `--baseline` vs the loop's many small directed calls.
| Expert attendants (the draft answer) | **BASELINE engine**: LLM answers from its weights; `verified=False`; source recorded (`model_weights`/`given_evidence`) | `floop/engine.py` |
| **knowledge** expert | **REAL pipeline** (2026-10-17): KG probe (entity+relation, stemmed) -> COMPOSE queries (deterministic, from question ∪ evidence — the old TRANSLATE LLM removed 23/10) -> en.wikipedia search -> fetch_rich (text + wikitext tables) -> section chunks -> lexical gate -> EXTRACT (verbatim quotes) -> containment check -> merge (4 contradiction cases) -> answer from quoted rows. Fallback: baseline LLM on pipeline failure. | `knowledge/` + `floop/engine.py:KnowledgeEngine` |
| Arrival check (type check + contradiction) | **STUB**: only UNKNOWN refusal | `machine._append_checked` |
| Execution branches over ambiguity (ALGORITHM §6-bis) | **REAL** (2026-10-23): lazy fork per reading of an ambiguous row with an open dependent; BranchView binds the reading (table never mutated), acquired knowledge shared + branch-tagged; death by contradiction/dead end/natural merge; nested sub-branches; conditional final answer composed by fixed code | `floop/branches.py` + `floop/machine.py:_run_branch` |
| Prover (stop condition, derivability) | **STUB**: question stack terminal | `machine._finish` |
| `user` expert | not wired — explicit failure row | `floop/engine.py` |
| Backtracking / retraction (TMS) | not in the draft (§5 comes with the prover) | — |
+319
View File
@@ -0,0 +1,319 @@
"""Execution branches (his branching design, 22-23/10 — now coded).
When an expert answers a question with SEVERAL defensible readings
(payload['ambiguous'] + alternatives, the knowledge expert's ablation
audit), the machine does NOT hand the alternatives to the next
subquestion's context (the rejected design — it only moves the
coin-flip into answer_kg) and does NOT collapse them inside ANSWER
(run L: 'Papandreou was the predecessor' — the exact rejected
behaviour). Instead, when a question DEPENDS on an ambiguous row, the
machine opens ONE LAZY EXECUTION BRANCH PER READING:
- a branch is a machine-level construct at floop DEPTH+1-like nesting,
but INSIDE this run: it owns its question stack and reads the
evidence through a BranchView that BINDS the ambiguous row to ONE
reading (a VIEW, never a store mutation — the same law as the
ablation mask);
- LAZY: the branch is born only when a dependent of the ambiguous row
becomes pickable — until then, nothing forks;
- SHARED: the knowledge acquired by every branch lands in the ONE
evidence table (the machine's working memory) and the KG/seen-index
live in the expert, shared by construction — a later branch reuses
what an earlier one gathered for free;
- per-branch is the READING of the ambiguous row + the subquestions
born under it; branch id rides every row's provenance;
- a branch DIES only by contradiction (its checked arrival refusing a
value), dead end (its terminal questions all failed — honest
UNKNOWN), or NATURAL MERGE (its answers converge with another
branch's — dedupe by value, keep the first) — never by an absurdity
judge (surprising-but-cited answers render, they are not
pocket-judged);
- the final answer is CONDITIONAL over surviving branches, composed
by FIXED CODE from the branch results — 'si et referies a president
d'Espanya -> Rajoy; si SI -> Papandreou; si PSOE -> qui sigui' —
never one reading chosen inside a synthesis prompt;
- nested ambiguity: a branch that hits its OWN ambiguous row forks
sub-branches under the same mechanism and the same caps.
Open by design (layer 3, a policy ABOVE this mechanism): asking the
user instead of running all branches = picking one branch upstairs.
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .state import EvidenceRow, EvidenceTable
# a branch result that is honestly nothing: dead end / contradiction /
# everything failed. The conditional render skips it (the branch's death
# is already in the notes), it never masquerades as an answer reading.
DEAD_END = "UNKNOWN"
def _norm(v: str) -> str:
"""Merge/dedupe key: casefolded alphanumerics (norm_name's machine-level
cousin — 'Rajoy' == 'rajoy', 'Pedro Sánchez' == 'Pedro Sanchez')."""
return re.sub(r"[^a-z0-9]+", " ", (v or "").casefold()).strip()
@dataclass
class BranchSpec:
"""One reading of one ambiguous row. The branch binds the row to
value; reading is the human-legible label ('as President of Spain')."""
id: str
ambiguous_eid: str
ambiguous_qid: str
value: str # the reading this branch binds
reading: str # label for the conditional render
origin: str = "" # the id of the branch that forked this one ("" = root)
# the open dependent SUBTREE copied into every branch of this fork,
# frozen at fork time (B1 consuming the originals must not change
# what B2 copies — the qids in qid order, deps rewired per branch)
subtree_qids: list[str] = field(default_factory=list)
@dataclass
class BranchResult:
"""What a branch concluded, for the conditional render."""
spec: BranchSpec
answer: str = "" # the branch's final answer (synthesized inside it)
status: str = "open" # open | answered | dead | merged
class BranchView:
"""The evidence table AS ONE BRANCH SEES IT.
The shared table is untouched — the ambiguous row is REPLACED in
this view by a synthetic row binding the branch's reading (same
qid, same answer_type, the reading's own quote/url, verified as
its source rows were — the reading IS the expert's pick or one of
its alternatives, each carried with quote+url by the audit). Rows
from other branches (provenance['branch'] set and different) are
HIDDEN: they answer questions that never existed in this world.
Everything else (rows with no branch tag, rows this branch appended)
passes through unchanged — acquired knowledge is shared.
"""
def __init__(self, table: "EvidenceTable", spec: BranchSpec) -> None:
self._table = table
self._spec = spec
def _bound_row(self) -> "EvidenceRow":
from .state import EvidenceRow
src = self._table.row(self._spec.ambiguous_eid)
payload = {k: v for k, v in (src.payload or {}).items()
if k not in ("ambiguous", "alternatives")}
payload["value"] = self._spec.value
payload["quote"] = self._reading_quote()
payload["branch_binding"] = True # the branch-fake's marker: this
# row IS the bound reading
if self._spec.origin:
payload["branch_reading"] = self._spec.reading
return EvidenceRow(
qid=src.qid, answer_type=src.answer_type, payload=payload,
engine=src.engine + ":branch-bind",
trace=[f"branch {self._spec.id}: ambiguous row bound to reading "
f"'{self._spec.value}'"],
provenance=dict(src.provenance, branch=self._spec.id),
verified=src.verified, note="")
def _reading_quote(self) -> str:
"""The reading's OWN quote when the row carries alternatives with
quotes; else the picked answer's quote (branch = the pick)."""
src = self._table.row(self._spec.ambiguous_eid)
for a in (src.payload.get("alternatives") or []):
if _norm(a.get("value", "")) == _norm(self._spec.value) and a.get("quote"):
return a["quote"]
return str(src.payload.get("quote", ""))
# -- the EvidenceTable interface the machine reads ---------------------
def row(self, eid: str) -> "EvidenceRow | None":
if eid == self._spec.ambiguous_eid:
return self._bound_row()
r = self._table.row(eid)
if r is not None and self._hidden(r):
return None
return r
def append(self, row: "EvidenceRow") -> "EvidenceRow":
"""A branch's new rows land in the SHARED table (acquired knowledge
is shared — a later branch reuses them) tagged with the branch id
(other branches' views hide them until they merge)."""
row.provenance["branch"] = self._spec.id
return self._table.append(row)
def rows(self) -> "list[EvidenceRow]":
return ([self._bound_row()] if self._bound_row() else []) + \
[r for r in self._table.rows() if r.eid != self._spec.ambiguous_eid
and not self._hidden(r)]
def for_question(self, qid: str) -> "list[EvidenceRow]":
return [r for r in self.rows() if r.qid == qid]
def dump(self) -> str:
from .state import EvidenceTable
flat = EvidenceTable()
for r in self.rows():
flat.append(type(r)(
answer_type=r.answer_type, payload=dict(r.payload),
engine=r.engine, qid=r.qid, trace=list(r.trace),
provenance=dict(r.provenance), verified=r.verified,
note=r.note, retracted=r.retracted))
return flat.dump()
def _hidden(self, r: "EvidenceRow") -> bool:
b = r.provenance.get("branch")
return bool(b) and b != self._spec.id
@dataclass
class BranchManager:
"""The fork bookkeeping. The machine asks 'should I fork on this row?'
(is it ambiguous AND does an open question depend on it), gets one
BranchSpec per reading, executes branches lazily, and renders the
surviving results conditionally.
The manager holds no execution logic — the machine runs each branch
as a plain FloopRun loop over its own stack; the manager owns the
specs, the merge policy, and the conditional render.
"""
max_branches: int = 6
specs: list[BranchSpec] = field(default_factory=list)
results: dict[str, BranchResult] = field(default_factory=dict)
dropped: list[str] = field(default_factory=list)
@property
def pending(self) -> list[BranchSpec]:
"""Specs not yet executed (FIFO — the picked reading runs first)."""
return [s for s in self.specs
if self.results.get(s.id) is None
or self.results[s.id].status == "open"]
def fork_specs(self, row: "EvidenceRow", origin: str = "",
subtree_qids: list[str] | None = None) -> list[BranchSpec]:
"""One spec per defensible reading of an ambiguous row whose open
dependent subtree (computed by the caller, frozen here) is non-
empty. LAZY LAW: an empty subtree means no fork — the ambiguity
is noted, the run continues on the pick.
`origin`: the branch we are inside when the fork fires ("" = the
root run) — nested ambiguity nests sub-branches under it.
Branch cap: past max_branches live specs, the extra readings are
dropped and NAMED (never silent)."""
if not row.payload.get("ambiguous"):
return []
alts = row.payload.get("alternatives") or []
readings = [(row.payload.get("value", ""), "the picked reading")]
readings += [(a.get("value", ""), a.get("value", ""))
for a in alts if a.get("value")]
specs = []
for i, (val, label) in enumerate(readings):
if not val or str(val).upper() == "UNKNOWN":
continue
bid = f"B{len(self.specs) + len(specs) + 1}"
spec = BranchSpec(
id=bid, ambiguous_eid=row.eid, ambiguous_qid=row.qid,
value=str(val),
reading=label if label and label != val else f"reading {bid}",
origin=origin,
subtree_qids=list(subtree_qids or []))
specs.append(spec)
if len(self.specs) + len(specs) > self.max_branches:
keep = self.max_branches - len(self.specs)
dropped = [s.reading for s in specs[keep:]]
specs = specs[:keep]
self.dropped = self.dropped + dropped
for s in specs:
self.specs.append(s)
self.results[s.id] = BranchResult(spec=s)
return specs
def record_answer(self, spec_id: str, answer: str) -> None:
res = self.results.get(spec_id)
if res is not None:
res.answer = answer
res.status = "answered"
def record_dead(self, spec_id: str) -> None:
res = self.results.get(spec_id)
if res is not None:
res.status = "dead"
def record_merge(self, spec_id: str, into: str) -> None:
res = self.results.get(spec_id)
if res is not None:
res.status = "merged"
res.answer = f"(merged with {into})"
def survivors(self, origin: str = "") -> list[BranchResult]:
"""Answered branches at one nesting level (origin), deduped by
normalized value — natural merge: two branches that concluded the
same thing are one conclusion. First-come order (the picked
reading usually leads)."""
seen: dict[str, BranchResult] = {}
order: list[BranchResult] = []
for res in self.results.values():
if res.status != "answered" or res.spec.origin != origin:
continue
key = _norm(res.answer)
if key and key in seen:
self.record_merge(res.spec.id, seen[key].spec.id)
continue
if key:
seen[key] = res
order.append(res)
return order
def conditional_answer(self, goal: str, origin: str = "") -> str:
"""The CONDITIONAL final answer, composed by FIXED CODE (run L
law: never collapse readings inside a synthesis prompt). All
surviving branch answers at one nesting level, one clause per
reading; a single survivor renders plain, its branch noted. A
branch whose own children answered carries its conditional as
its recorded answer — nesting is baked in, not re-rendered.
Dead branches are already in the notes; the render never
invents their content."""
alive = self.survivors(origin)
dropped = self.dropped
if not alive:
parts = ["No reading reached an answer."]
if dropped:
parts.append(f"(branch cap: readings dropped: {', '.join(dropped)})")
return " ".join(parts)
if len(alive) == 1:
r = alive[0]
out = f"{r.answer} (reading: {r.spec.reading})"
if dropped:
out += f" — other readings hit the branch cap: {', '.join(dropped)}"
return out
clauses = [f"if you meant {res.spec.reading} -> {res.answer}"
for res in alive]
out = " | ".join(clauses)
if dropped:
out += f" | (branch cap: {', '.join(dropped)} not run)"
return out
def open_subtree(stack, ambiguous_qid: str) -> list[str]:
"""The OPEN dependent subtree below one question: direct AND transitive
open dependents, qids in discovery order. LAZY: an empty list means
no fork — a branch is born only when someone needs the reading.
Frozen at fork time: every branch of the fork copies the SAME list
(the first branch consuming the originals must not change what the
second copies)."""
found: dict[str, str] = {} # orig qid -> branch copy qid (filled later)
order: list[str] = []
changed = True
while changed:
changed = False
for q in stack.items:
if (q.status == "open" and not q.parent_goal
and q.qid not in order
and any(d in found or d == ambiguous_qid for d in q.deps)):
order.append(q.qid)
found[q.qid] = ""
changed = True
return order
+177 -1
View File
@@ -16,6 +16,8 @@ from dataclasses import dataclass, field
from .engine import CATALOG, LLMExpertEngine, UserRequestEngine
from .setops import detect_setop, setop_row
from .branches import (BranchManager, BranchResult, BranchSpec, BranchView,
DEAD_END, open_subtree)
from .dspy_modules import FloopModules
from .state import (AnswerType, Budget, BudgetExhausted, EvidenceRow,
EvidenceTable, OpenQuestion, QuestionStack, instantiate)
@@ -101,6 +103,13 @@ class FloopRun:
self.knowledge_engine = knowledge_engine # None -> baseline LLM expert
self.notes: list[str] = []
self.engine_calls = 0
# BRANCHING (his design, 22-23/10): the fork bookkeeping. Specs are
# created lazily (only when a dependent of an ambiguous row exists);
# the shared table/stack stay THE run's own — a branch reads the
# table through a BranchView that binds the ambiguous row to its
# reading and hides other branches' rows.
self.branches = BranchManager()
self._current_branch = "" # "" = the root run; else the branch id
# RE-ASK METER (run L): dspy's adapter fallback fires extra LM calls
# the budget never charged. The prompt-log callback sees them; wire
# its meter to our budget so the count is honest. The BEHAVIOUR of
@@ -134,6 +143,14 @@ class FloopRun:
self._init_decompose()
while True:
try:
# BRANCHING: a fork pending means an ambiguous row gained a
# dependent — its readings each own a world now. Run the
# branches to their end BEFORE the main loop continues
# (their conclusions/notes land in the shared table/notes;
# the conditional render happens at _finish).
while self.branches.pending:
spec = self.branches.pending[0]
self._run_branch(spec)
q = self.stack.pickable(self.table)
if q is None:
if self.stack.all_terminal():
@@ -379,6 +396,135 @@ class FloopRun:
note=(f"partial: {len(nums)} of {len(entity_rows)} values summed"
if partial else ""))
def _run_branch(self, spec: BranchSpec) -> None:
"""Execute ONE branch to its end, inside this run.
The branch is a NESTED LOOP SESSION, not a child FloopRun: it
swaps the machine's table view (BranchView binds the ambiguous
row to this branch's reading, hides other branches' rows) and
question stack (the dependent questions re-asked inside this
world), runs the same fixed loop, and restores state after.
Acquired knowledge (rows) lands in the SHARED table tagged with
the branch id; notes and engine_calls accumulate on the run; the
budget is the run's own (shared pool — his design: llm_calls
pool shared, depth+1 burns the existing depth counter).
Death: contradiction (a checked arrival refuses the branch's
values — the row lands with value UNKNOWN and its questions
fail), dead end (the branch's terminal questions all failed),
or natural merge (its answer equals an earlier branch's —
recorded at survivors()). Never an absurdity judge.
"""
view = BranchView(self.table, spec)
self.streams.warn(
f"BRANCH {spec.id} starts: reading '{spec.value[:60]}' "
f"(bound from {spec.ambiguous_eid})")
main_table, main_stack = self.table, self.stack
main_branch = self._current_branch
self.table = view # type: ignore[assignment]
self._current_branch = spec.id
# the branch's stack: the dependent subtree FROZEN at fork time —
# the same question set for every branch of the fork (B1 consuming
# the originals changed nothing about what B2 copies). Copied
# inside this world with BRANCH-SCOPED qids (a collision would make
# a copy look already-answered) and deps rewired to the copies.
branch_stack = QuestionStack(spec.value)
by_orig = {q.qid: q for q in main_stack.items}
copies_by_orig: dict[str, str] = {}
for orig_qid in spec.subtree_qids:
orig = by_orig.get(orig_qid)
if orig is None:
continue
nq = branch_stack.add(OpenQuestion(
text=orig.text, answer_type=orig.answer_type,
deps=[], reason=f"branch {spec.id} of {orig_qid}"))
nq.qid = f"{spec.id}.{orig_qid}"
# deps: the ambiguous row is BOUND (present in the view with its
# reading fixed — not a dependency anymore); deps on copied
# siblings point at the COPIES; deps on other already-answered
# questions keep the reference (their rows live in the shared table)
nq.deps = [copies_by_orig.get(d, d) for d in orig.deps
if d != spec.ambiguous_qid]
copies_by_orig[orig_qid] = nq.qid
for q in main_stack.items:
if q.qid in copies_by_orig:
q.status = "answered"
q.reason = f"answered by branches over {spec.ambiguous_qid}"
self.stack = branch_stack # type: ignore[assignment]
try:
while True:
try:
# NESTED FORK: an ambiguous row inside this branch with
# its own dependent opens sub-branches (origin=this
# branch); run them to their end before continuing —
# the same lazy law, one level deeper.
while any(s.origin == spec.id
for s in self.branches.pending):
sub = next(s for s in self.branches.pending
if s.origin == spec.id)
self._run_branch(sub)
q = self.stack.pickable(self.table)
if q is None:
if self.stack.all_terminal():
break
if self.budget.missing_used >= self.budget.missing_extensions:
self.notes.append(
"missing-extension limit reached inside a branch")
break
self._missing_round()
continue
self._route_and_execute(q)
except BudgetExhausted:
self.notes.append(
f"budget exhausted inside branch {spec.id} "
f"at llm_calls={self.budget.llm_calls}")
break
except Exception as e: # noqa: BLE001
if _lm_dead(e):
self.notes.append(
f"LM unreachable inside branch {spec.id}; "
f"branch aborted honestly")
break
raise
# the branch's conclusion. A branch whose OWN children
# answered carries the CHILDREN's conditional as its answer
# (nesting composes); otherwise synthesize from its rows.
answer = ""
kids = [s for s in self.branches.specs if s.origin == spec.id]
if kids and branch_stack.open_count() == 0:
answer = self.branches.conditional_answer(self.query, origin=spec.id)
if answer and not answer.startswith("No reading"):
self.branches.record_answer(spec.id, answer)
self.streams.state(
f"branch {spec.id} concluded (nested, "
f"{len(kids)} sub-branches): {answer[:80]}", think=True)
else:
self.branches.record_dead(spec.id)
self.notes.append(
f"branch {spec.id}: dead — no sub-reading survived")
elif (branch_stack.open_count() == 0 and branch_stack.items[1:]
and any(i.status == "answered"
for i in branch_stack.items[1:])):
try:
self._charge()
answer = self.modules.synthesize(
self.query, view.dump(), unverified=True)
self.branches.record_answer(spec.id, answer)
self.streams.state(
f"branch {spec.id} concluded: {answer[:80]}", think=True)
except (BudgetExhausted, Exception) as e: # noqa: BLE001
self.branches.record_dead(spec.id)
self.notes.append(f"branch {spec.id}: synthesis failed ({e})")
else:
self.branches.record_dead(spec.id)
self.notes.append(
f"branch {spec.id}: dead — no reading survived "
f"(all dependents failed)")
finally:
self.table = main_table
self.stack = main_stack
self._current_branch = main_branch
def _route_and_execute(self, q: OpenQuestion) -> None:
# SETOP GUARD: a count over list rows already in evidence is
# computation, not routing — the machine computes it deterministically
@@ -518,6 +664,25 @@ class FloopRun:
f"other readings: " + "; ".join(
a.get("value") for a in alts[:3]))
self.table.append(row)
# BRANCHING TRIGGER (his design): an ambiguous row with an OPEN
# dependent subtree forks the run into one branch per reading —
# LAZY (empty subtree: no fork, the ambiguity stays a note, the
# pick rides), the subtree FROZEN here so every branch of the
# fork copies the same questions (the first branch consuming the
# originals must not change what the second copies).
if row.payload.get("ambiguous"):
subtree = open_subtree(self.stack, q.qid)
if subtree:
specs = self.branches.fork_specs(
row, origin=self._current_branch, subtree_qids=subtree)
if specs:
self.notes.append(
f"{q.qid}: forking {len(specs)} branches over the "
f"readings of {row.eid}: "
+ "; ".join(f"{s.id}={s.value[:40]}" for s in specs))
self.streams.warn(
f"FORK {q.qid} over {row.eid}: {len(specs)} readings "
f"-> branches {', '.join(s.id for s in specs)}")
if str(row.payload.get("value", "")).strip().upper() == "UNKNOWN":
q.status = "failed"
q.reason = "expert returned UNKNOWN"
@@ -566,6 +731,17 @@ class FloopRun:
def _finish(self, t0: float) -> RunReport:
verified = False # STUB prover — v0.2: derivability check (clingo/Z3)
answer = ""
if self.branches.specs:
# CONDITIONAL ANSWER (run L law): several readings survived —
# the answer is composed by FIXED CODE from the branch results,
# never by one synthesis prompt choosing a reading inside itself.
answer = self.branches.conditional_answer(self.query)
self.streams.final(answer)
self.notes.append(
f"conditional answer over {len(self.branches.specs)} branches: "
+ "; ".join(f"{s.id}={self.branches.results[s.id].status}"
for s in self.branches.specs))
else:
try:
self._charge()
self.streams.call("ANSWER", f"synthesize answer for: {self.query[:80]}",
@@ -578,7 +754,7 @@ class FloopRun:
except Exception as e: # noqa: BLE001 — a dead LM answers nothing
if _lm_dead(e):
self.notes.append(f"LM unreachable before synthesis ({type(e).__name__}); "
"evidence is kept, the answer is not written")
f"evidence is kept, the answer is not written")
else:
raise
return RunReport(
+372
View File
@@ -0,0 +1,372 @@
"""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")