"""PR-10b tests: typed INIT via dspy native structured output. Run I taught the pipe parser every defensive trick (line-number shifting, bare-number dropping). The typed migration removes the string contract entirely: dspy renders the Subquestion schema (enum answer_type, list[int] depends_on) into the prompt and parses responses back into typed objects — no Python string parsing on the production path. Laws under test: 1. The typed path E2E: a model response (raw text, through a REAL dspy.LM engine) parses into typed Subquestions; the machine dicts carry text, depends_on ints, and the AnswerType enum. 2. Bare-number texts are still dropped (run-I law, now in _subs_from_typed). 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. 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 import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) 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.machine import FloopRun import tempfile as tf from floop.stream import RunStreams from floop.llm import PromptLogCallback, install_prompt_log def _lm(scripted_raw: str) -> None: """A dspy.LM whose engine returns raw text — the REAL wire shape. cache=False: dspy persists responses to disk keyed by (model, prompt) and would cross-contaminate tests sharing the fake model name.""" 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 subs[0]["text"] == "Which presidency does Pedro Sanchez hold?" assert subs[0]["deps"] == [] and subs[0]["answer_type"] == AnswerType.OPEN assert subs[1]["deps"] == [1] print("ok: typed INIT parses through the real adapter path (E2E)") def test_bare_number_text_dropped(): raw = '''[[ ## subquestions ## ]] [{"text": "1", "depends_on": [], "answer_type": "OPEN"}, {"text": "Who held that office before?", "depends_on": [], "answer_type": "OPEN"}] [[ ## completed ## ]]''' _lm(raw) subs, _ = FloopModules().init_decompose("Who was the President before?") assert [s["text"] for s in subs] == ["Who held that office before?"], subs print("ok: bare-number texts dropped (run-I law survives typing)") def test_garbage_degrades(): # run-I shape: the model wrote its own line numbers, none parse to a # valid schema — after dspy's re-ask the AdapterParseError carries the # garbage; init_decompose must signal (subs=[], raw non-empty) garbage = "1\n2" _lm(garbage) subs, raw = FloopModules().init_decompose("Who was the President before?") assert subs == [] and raw and raw.strip(), (subs, raw) print(f"ok: schema-violating garbage -> degrade signal (raw: {raw[:20]!r})") def test_garbage_machine_degrades_to_original(): b = Budget(max_llm_calls=40, max_depth=2, max_retries=3, missing_extensions=1, min_child_budget=4) 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() q1 = rep.questions[0] assert q1[2] and not q1[2].strip().isdigit(), q1 assert "Pedro Sanchez" in q1[2] 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") def test_empty_stays_atomic(): b = Budget(max_llm_calls=40, max_depth=2, max_retries=3, missing_extensions=1, min_child_budget=4) class AtomicModules: def init_decompose(self, question): return [], "" # truly empty — atomic 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=[]) streams = RunStreams("raw resp test", verbose=False, runs_dir=tf.mkdtemp()) cb = PromptLogCallback(streams) _lm(_GOOD) dspy.configure(callbacks=[cb]) FloopModules().init_decompose("Who was the President before Pedro Sanchez?") f = next((streams.run_dir / "prompts").glob("01-*.txt")) content = f.read_text() assert "# RAW RESPONSE" in content, content assert "presidency does Pedro Sanchez" in content, content print(f"ok: raw response appended to {f.name}") dspy.settings.configure(callbacks=[]) if __name__ == "__main__": test_typed_init_e2e() test_bare_number_text_dropped() test_garbage_degrades() test_garbage_machine_degrades_to_original() test_empty_stays_atomic() test_prompt_log_still_captures_raw() print("\ntyped-INIT tests passed")