floop: typed INIT+MISSING via dspy structured output (Subquestion)

The typed-output migration starts with the machine's decomposition step:
the pipe contract ('text | deps | answer_type' lines) is gone — dspy
renders the Subquestion schema natively.

- Subquestion(BaseModel): text + depends_on: list[int] +
  answer_type: AnswerType (enum rendered into the prompt's JSON schema)
- InitSignature/MissingSignature.subquestions: list[Subquestion]
- init_decompose keeps the (subs, raw) machine contract: a
  schema-violating response raises AdapterParseError after dspy's own
  JSON re-ask; its lm_response becomes the degrade signal so the
  run-I law survives typing — the machine still routes the ORIGINAL
  question, never garbage
- bare-number texts still dropped (now in _subs_from_typed)
- parse_subquestions kept as LEGACY for tests

Tests rewritten for the REAL adapter path (RawEngine + cache=False):
DummyLM bypasses the adapter; and dspy's disk cache (~/.dspy_cache)
cross-contaminates scripted tests sharing a fake model name — both
pitfalls found while migrating.

VERIFIED:
- suite 12/12 green (robust_init rewritten: 6/6 — E2E typed parse,
  bare-number drop, garbage degrade, machine degrade, atomic case,
  raw-response prompt log)
- live E2E (ollama-cloud glm-5.3-flash): INIT renders the enum schema,
  glm returns depends_on ints + valid enums, machine dicts clean,
  full run answers Rajoy with citations. NOTE: dspy's disk cache made
  the second run's INIT a 0.2s cache hit — runs share the cache.
This commit is contained in:
2026-10-22 15:02:12 +02:00
parent 109885773c
commit c7bd010f47
2 changed files with 193 additions and 144 deletions
+49 -16
View File
@@ -9,22 +9,34 @@ from __future__ import annotations
import re import re
import dspy import dspy
from pydantic import BaseModel
from .state import AnswerType from .state import AnswerType
try:
from dspy.utils.exceptions import AdapterParseError
except ImportError: # pragma: no cover — dspy <3.x
AdapterParseError = type("AdapterParseError", (Exception,), {"lm_response": ""})
class Subquestion(BaseModel):
"""One open subquestion in the goal's decomposition."""
text: str = dspy.OutputField(desc="the subquestion, phrased as a question")
depends_on: list[int] = dspy.OutputField(
desc="1-based positions of the subquestions whose answers this one needs first; empty when none")
answer_type: AnswerType = dspy.OutputField(
desc="OPEN for a single value, FUNCTION for a formula, INTERVAL for a range, "
"CONSTANT for a universal constant, LIST for an enumeration of things")
class InitSignature(dspy.Signature): class InitSignature(dspy.Signature):
"""You are the INIT step of a reasoning machine. Using ONLY concepts literally """You are the INIT step of a reasoning machine. Using ONLY concepts literally
present in the question plus a generic planning scaffold (number, method, present in the question plus a generic planning scaffold (number, method,
machine, resources, dependencies), ask: what information or knowledge do I machine, resources, dependencies), ask: what information or knowledge do I
need to answer this? Write 1-4 open subquestions in dependency order. need to answer this? Write 1-4 open subquestions in dependency order."""
Use answer_type LIST when the subquestion asks for an enumeration of
things (which countries, what rivers, list all members...)."""
question: str = dspy.InputField() question: str = dspy.InputField()
subquestions: str = dspy.OutputField( subquestions: list[Subquestion] = dspy.OutputField(
desc="one subquestion per line, pipe-separated fields: " desc="1-4 subquestions in dependency order; empty when the question is atomic")
"text | depends_on (line numbers or 'none') | answer_type (OPEN|FUNCTION|INTERVAL|CONSTANT|LIST)"
)
class RouteSignature(dspy.Signature): class RouteSignature(dspy.Signature):
@@ -60,9 +72,8 @@ class MissingSignature(dspy.Signature):
the evidence.""" the evidence."""
goal: str = dspy.InputField() goal: str = dspy.InputField()
evidence: str = dspy.InputField() evidence: str = dspy.InputField()
subquestions: str = dspy.OutputField( subquestions: list[Subquestion] = dspy.OutputField(
desc="one subquestion per line, pipe-separated: text | depends_on ('none' or #E refs) | answer_type" desc="1-3 subquestions that would close the gap; empty when nothing helps")
)
class AnswerSignature(dspy.Signature): class AnswerSignature(dspy.Signature):
@@ -89,14 +100,36 @@ class FloopModules:
def init_decompose(self, question: str) -> tuple[list[dict], str]: def init_decompose(self, question: str) -> tuple[list[dict], str]:
"""(parsed subquestions, raw model output). The machine decides what """(parsed subquestions, raw model output). The machine decides what
an empty parse means: empty raw = the question is atomic; non-empty an empty parse means: empty raw = the question is atomic; non-empty
raw that parses to nothing = model garbage (run I) — degrade.""" raw that parses to nothing = model garbage (run I) — degrade.
pred = self.init(question=question)
raw = pred.subquestions or "" Typed output: a response that violates the Subquestion schema raises
return parse_subquestions(raw), raw AdapterParseError AFTER dspy's own JSON re-ask; its lm_response IS
the raw garbage — hand it back as the degrade signal."""
try:
pred = self.init(question=question)
except AdapterParseError as e:
return [], (e.lm_response or "unparseable response")
return self._subs_from_typed(pred.subquestions), ""
@staticmethod
def _subs_from_typed(subs) -> list[dict]:
"""Typed Subquestion objects -> machine dicts. A bare number is a
line number, never a question (run I law kept)."""
out = []
for s in (subs or []):
text = (s.text or "").strip()
if not text or text.isdigit():
continue
out.append({"text": text, "deps": list(s.depends_on or []),
"answer_type": s.answer_type})
return out
def missing_decompose(self, goal: str, evidence: str) -> list[dict]: def missing_decompose(self, goal: str, evidence: str) -> list[dict]:
pred = self.missing(goal=goal, evidence=evidence) try:
return parse_subquestions(pred.subquestions) pred = self.missing(goal=goal, evidence=evidence)
except AdapterParseError:
return []
return self._subs_from_typed(pred.subquestions)
def route_question(self, question: str, catalog: str, evidence: str) -> tuple[str, str]: def route_question(self, question: str, catalog: str, evidence: str) -> tuple[str, str]:
pred = self.route(question=question, catalog=catalog, evidence=evidence) pred = self.route(question=question, catalog=catalog, evidence=evidence)
+144 -128
View File
@@ -1,20 +1,24 @@
"""PR-6 tests: INIT parsing robustness + the raw-response log (run I). """PR-10b tests: typed INIT via dspy native structured output.
Run I: asked 'Who was the President before Pedro Sanchez?' the INIT LM Run I taught the pipe parser every defensive trick (line-number shifting,
answered with its own line numbers as an extra pipe field bare-number dropping). The typed migration removes the string contract
('1 | Who was Pedro Sanchez? | none | OPEN'), the naive parse took '1' entirely: dspy renders the Subquestion schema (enum answer_type,
and '2' as the subquestion texts, ROUTE classified Q1='1' as numeric and list[int] depends_on) into the prompt and parses responses back into
the machine burned 4 calls on garbage before luck produced the answer. typed objects — no Python string parsing on the production path.
Three laws under test: Laws under test:
1. parse_subquestions shifts the numbered form and never accepts a bare 1. The typed path E2E: a model response (raw text, through a REAL
number as a subquestion text. dspy.LM engine) parses into typed Subquestions; the machine dicts
2. The machine degrades to the ORIGINAL question as one OPEN carry text, depends_on ints, and the AnswerType enum.
subquestion when nothing parses (a routable question is text). 2. Bare-number texts are still dropped (run-I law, now in
3. The prompt log appends the RAW LM response to the prompt file — the _subs_from_typed).
parsed OUTPUT line can lie by omission. 3. A schema-violating response (AdapterParseError, even after dspy's
own JSON re-ask) becomes the degrade signal: (subs=[], raw) — the
machine routes the ORIGINAL question, never garbage.
4. The atomic case (empty subquestions list) stays atomic.
No network, no real LLM. Run: .venv/bin/python tests/robust_init.py No network. The engine returns raw text — DummyLM would bypass the
adapter and test nothing. Run: .venv/bin/python tests/robust_init.py
""" """
from __future__ import annotations from __future__ import annotations
@@ -23,151 +27,163 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from floop.dspy_modules import parse_subquestions import dspy
import warnings
warnings.filterwarnings("ignore")
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
from floop.dspy_modules import FloopModules, Subquestion
from floop.state import AnswerType, Budget from floop.state import AnswerType, Budget
from floop.machine import FloopRun from floop.machine import FloopRun
import tempfile as tf
from floop.stream import RunStreams
from floop.llm import PromptLogCallback, install_prompt_log
# --- 1) the parser -----------------------------------------------------------
def test_parse_numbered_lines(): def _lm(scripted_raw: str) -> None:
# the exact run-I shape: model line numbers as an extra first field """A dspy.LM whose engine returns raw text — the REAL wire shape.
raw = ("1 | Who was the President of Spain before Pedro Sanchez? | none | OPEN\n" cache=False: dspy persists responses to disk keyed by (model, prompt)
"2 | When did that president's term end? | 1 | OPEN") and would cross-contaminate tests sharing the fake model name."""
subs = parse_subquestions(raw) class RawEngine:
def complete(self, request):
return Response(
id="x", model="t",
message=Message(role="assistant",
parts=(TextPart(text=scripted_raw),)),
finish_reason="stop",
usage=Usage(input_tokens=1, output_tokens=1, total_tokens=2))
dspy.configure(lm=dspy.LM("openai/test", engine=RawEngine(),
cache=False))
# a canonical typed response, markers and all
_GOOD = '''[[ ## subquestions ## ]]
[{"text": "Which presidency does Pedro Sanchez hold?", "depends_on": [], "answer_type": "OPEN"},
{"text": "Who held that same office before him?", "depends_on": [1], "answer_type": "OPEN"}]
[[ ## completed ## ]]'''
def test_typed_init_e2e():
_lm(_GOOD)
subs, raw = FloopModules().init_decompose(
"Who was the President before Pedro Sanchez?")
assert len(subs) == 2, subs assert len(subs) == 2, subs
assert subs[0]["text"] == "Who was the President of Spain before Pedro Sanchez?" assert subs[0]["text"] == "Which presidency does Pedro Sanchez hold?"
assert subs[0]["deps"] == [] assert subs[0]["deps"] == [] and subs[0]["answer_type"] == AnswerType.OPEN
assert subs[0]["answer_type"] == AnswerType.OPEN
assert subs[1]["deps"] == [1], subs[1]
print("ok: numbered-line form shifted (text, deps, type all intact)")
def test_parse_bare_number_lines_dropped():
# even if the number survives as text, it must be dropped — never routable
raw = "1 | none | OPEN\n2 | none | OPEN"
subs = parse_subquestions(raw)
assert subs == [], subs
print("ok: bare-number texts dropped (nothing routable = '1' or '2')")
def test_parse_enumerator_prefix():
# '1. Who was ...' inside the FIRST field — not a separate field
raw = ("1. Who was the President before Pedro Sanchez? | none | OPEN\n"
"2. When did his term end? | 1 | OPEN")
subs = parse_subquestions(raw)
assert len(subs) == 2, subs
assert subs[0]["text"] == "Who was the President before Pedro Sanchez?"
assert subs[1]["deps"] == [1] assert subs[1]["deps"] == [1]
print("ok: enumerator prefixes stripped from the text field") print("ok: typed INIT parses through the real adapter path (E2E)")
def test_parse_happy_path_unchanged(): def test_bare_number_text_dropped():
# the old well-formed cases keep working (regression guard) raw = '''[[ ## subquestions ## ]]
subs = parse_subquestions( [{"text": "1", "depends_on": [], "answer_type": "OPEN"},
"1. How many qubits are needed? | none | FUNCTION\n" {"text": "Who held that office before?", "depends_on": [], "answer_type": "OPEN"}]
"2. What is the clock speed? | 1 | INTERVAL\n")
assert subs[0]["text"].endswith("needed?") and subs[0]["deps"] == [] [[ ## completed ## ]]'''
assert subs[1]["deps"] == [1] and subs[1]["answer_type"] == AnswerType.INTERVAL _lm(raw)
assert parse_subquestions("") == [] subs, _ = FloopModules().init_decompose("Who was the President before?")
assert parse_subquestions("|||\n1 | none | OPEN") == [] assert [s["text"] for s in subs] == ["Who held that office before?"], subs
print("ok: well-formed lines parse exactly as before") print("ok: bare-number texts dropped (run-I law survives typing)")
# --- 2) the INIT degrade ----------------------------------------------------- def test_garbage_degrades():
# run-I shape: the model wrote its own line numbers, none parse to a
class GarbageInitModules: # valid schema — after dspy's re-ask the AdapterParseError carries the
"""INIT returns zero parseable subquestions (the run-I transcript).""" # garbage; init_decompose must signal (subs=[], raw non-empty)
garbage = "1\n2"
def init_decompose(self, question): _lm(garbage)
# (subs, raw): nothing parses, but the model DID write — degrade subs, raw = FloopModules().init_decompose("Who was the President before?")
return (parse_subquestions("1 | none | OPEN\n2 | 1 | OPEN"), assert subs == [] and raw and raw.strip(), (subs, raw)
"1 | none | OPEN\n2 | 1 | OPEN") print(f"ok: schema-violating garbage -> degrade signal (raw: {raw[:20]!r})")
def missing_decompose(self, goal, evidence):
return [{"text": "fallback question?", "deps": [], "answer_type": "OPEN"}]
def route_question(self, question, catalog, evidence):
assert not question.strip().isdigit(), f"garbage routed: {question!r}"
return "knowledge", "text question"
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
return {"value": "Mariano Rajoy", "source_quote": "",
"confidence": "high"}
def synthesize(self, goal, evidence, unverified):
return "Mariano Rajoy"
def test_init_degrades_to_original_question(): def test_garbage_machine_degrades_to_original():
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3, b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
missing_extensions=1, min_child_budget=4) missing_extensions=1, min_child_budget=4)
fm = GarbageInitModules()
run = FloopRun("Who was the President before Pedro Sanchez?", b, modules=fm) class GarbageInitModules:
"""INIT returns zero parseable subquestions (the run-I transcript)."""
def init_decompose(self, question):
return [], "1\n2" # garbage raw — degrade path
def missing_decompose(self, goal, evidence):
return [{"text": "fallback question?", "deps": [],
"answer_type": "OPEN"}]
def route_question(self, question, catalog, evidence):
assert not question.strip().isdigit(), f"garbage routed: {question!r}"
return "knowledge", "text question"
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
return {"value": "Mariano Rajoy", "source_quote": "",
"confidence": "high"}
def synthesize(self, goal, evidence, unverified):
return "Mariano Rajoy"
run = FloopRun("Who was the President before Pedro Sanchez?", b,
modules=GarbageInitModules())
rep = run.run() rep = run.run()
# the machine must have routed the ORIGINAL question, not '1'/'2'
assert rep is not None
q1 = rep.questions[0] q1 = rep.questions[0]
assert q1[2] and not q1[2].strip().isdigit(), q1 # text, never a bare number assert q1[2] and not q1[2].strip().isdigit(), q1
assert "Pedro Sanchez" in q1[2] assert "Pedro Sanchez" in q1[2]
assert all(not q[2].strip().isdigit() for q in rep.questions), rep.questions assert all(not q[2].strip().isdigit() for q in rep.questions), rep.questions
print("ok: INIT degrade routes the original question as one OPEN subq") print("ok: INIT degrade routes the ORIGINAL question as one OPEN subq")
# --- 3) the raw-response log -------------------------------------------------- def test_empty_stays_atomic():
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
missing_extensions=1, min_child_budget=4)
def test_prompt_log_captures_raw_response(): class AtomicModules:
import dspy def init_decompose(self, question):
from dspy.utils.dummies import DummyLM return [], "" # truly empty — atomic
import tempfile as tf
from floop.llm import PromptLogCallback, install_prompt_log
from floop.stream import RunStreams
def missing_decompose(self, goal, evidence):
return []
def route_question(self, question, catalog, evidence):
return "knowledge", "text"
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
return {"value": "299792458", "source_quote": "", "confidence": "high"}
def synthesize(self, goal, evidence, unverified):
return "299792458"
rep = FloopRun("What is the speed of light?", b,
modules=AtomicModules()).run()
assert len(rep.questions) == 1, rep.questions
assert rep.questions[0][0] == "Q0"
assert rep.questions[0][2] == "What is the speed of light?"
print("ok: empty raw stays atomic (no fabricated subquestion)")
def test_prompt_log_still_captures_raw():
# PR-4/9 law: the RAW LM response is appended to the prompt file — now
# for the typed path too (the engine's raw text is what gets logged)
dspy.settings.configure(callbacks=[]) dspy.settings.configure(callbacks=[])
streams = RunStreams("raw resp test", verbose=False, runs_dir=tf.mkdtemp()) streams = RunStreams("raw resp test", verbose=False, runs_dir=tf.mkdtemp())
cb = PromptLogCallback(streams) cb = PromptLogCallback(streams)
dspy.configure(lm=DummyLM([ _lm(_GOOD)
{"subquestions": "1 | Who was Pedro Sanchez? | none | OPEN"} dspy.configure(callbacks=[cb])
]), callbacks=[cb]) FloopModules().init_decompose("Who was the President before Pedro Sanchez?")
class Sig(dspy.Signature):
question: str = dspy.InputField()
subquestions: str = dspy.OutputField()
dspy.Predict(Sig)(question="Who was the President before Pedro Sanchez?")
f = next((streams.run_dir / "prompts").glob("01-*.txt")) f = next((streams.run_dir / "prompts").glob("01-*.txt"))
content = f.read_text() content = f.read_text()
assert "# RAW RESPONSE" in content, content assert "# RAW RESPONSE" in content, content
assert "Who was Pedro Sanchez?" in content, content assert "presidency does Pedro Sanchez" in content, content
print(f"ok: raw response appended to {f.name}") print(f"ok: raw response appended to {f.name}")
dspy.settings.configure(callbacks=[]) dspy.settings.configure(callbacks=[])
def test_empty_raw_stays_atomic():
"""Empty RAW (the model truly returned nothing) keeps the old law: the
goal is atomic — stop and synthesize, never fabricate a subquestion."""
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
missing_extensions=1, min_child_budget=4)
class AtomicModules(GarbageInitModules):
def init_decompose(self, question):
return [], ""
fm = AtomicModules()
rep = FloopRun("What is the speed of light?", b, modules=fm).run()
# atomic: INIT added no subquestions — only the goal's own Q0 remains
assert len(rep.questions) == 1, rep.questions
assert rep.questions[0][0] == "Q0", rep.questions
assert rep.questions[0][2] == "What is the speed of light?", rep.questions
print("ok: empty raw stays atomic (no fabricated subquestion)")
if __name__ == "__main__": if __name__ == "__main__":
test_parse_numbered_lines() test_typed_init_e2e()
test_parse_bare_number_lines_dropped() test_bare_number_text_dropped()
test_parse_enumerator_prefix() test_garbage_degrades()
test_parse_happy_path_unchanged() test_garbage_machine_degrades_to_original()
test_init_degrades_to_original_question() test_empty_stays_atomic()
test_empty_raw_stays_atomic() test_prompt_log_still_captures_raw()
test_prompt_log_captures_raw_response() print("\ntyped-INIT tests passed")
print("\nrobust_init tests passed")