"""PR-6 tests: INIT parsing robustness + the raw-response log (run I). Run I: asked 'Who was the President before Pedro Sanchez?' the INIT LM answered with its own line numbers as an extra pipe field ('1 | Who was Pedro Sanchez? | none | OPEN'), the naive parse took '1' and '2' as the subquestion texts, ROUTE classified Q1='1' as numeric and the machine burned 4 calls on garbage before luck produced the answer. Three laws under test: 1. parse_subquestions shifts the numbered form and never accepts a bare number as a subquestion text. 2. The machine degrades to the ORIGINAL question as one OPEN subquestion when nothing parses (a routable question is text). 3. The prompt log appends the RAW LM response to the prompt file — the parsed OUTPUT line can lie by omission. No network, no real LLM. 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)) from floop.dspy_modules import parse_subquestions from floop.state import AnswerType, Budget from floop.machine import FloopRun # --- 1) the parser ----------------------------------------------------------- def test_parse_numbered_lines(): # the exact run-I shape: model line numbers as an extra first field raw = ("1 | Who was the President of Spain before Pedro Sanchez? | none | OPEN\n" "2 | When did that president's term end? | 1 | OPEN") subs = parse_subquestions(raw) assert len(subs) == 2, subs assert subs[0]["text"] == "Who was the President of Spain before Pedro Sanchez?" assert subs[0]["deps"] == [] 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] print("ok: enumerator prefixes stripped from the text field") def test_parse_happy_path_unchanged(): # the old well-formed cases keep working (regression guard) 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 assert parse_subquestions("") == [] assert parse_subquestions("|||\n1 | none | OPEN") == [] print("ok: well-formed lines parse exactly as before") # --- 2) the INIT degrade ----------------------------------------------------- class GarbageInitModules: """INIT returns zero parseable subquestions (the run-I transcript).""" def init_decompose(self, question): # (subs, raw): nothing parses, but the model DID write — degrade return (parse_subquestions("1 | none | OPEN\n2 | 1 | OPEN"), "1 | none | OPEN\n2 | 1 | OPEN") 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(): b = Budget(max_llm_calls=40, max_depth=2, max_retries=3, missing_extensions=1, min_child_budget=4) fm = GarbageInitModules() run = FloopRun("Who was the President before Pedro Sanchez?", b, modules=fm) rep = run.run() # the machine must have routed the ORIGINAL question, not '1'/'2' assert rep is not None q1 = rep.questions[0] assert q1[2] and not q1[2].strip().isdigit(), q1 # text, never a bare number 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") # --- 3) the raw-response log -------------------------------------------------- def test_prompt_log_captures_raw_response(): import dspy from dspy.utils.dummies import DummyLM import tempfile as tf from floop.llm import PromptLogCallback, install_prompt_log from floop.stream import RunStreams dspy.settings.configure(callbacks=[]) streams = RunStreams("raw resp test", verbose=False, runs_dir=tf.mkdtemp()) cb = PromptLogCallback(streams) dspy.configure(lm=DummyLM([ {"subquestions": "1 | Who was Pedro Sanchez? | none | OPEN"} ]), callbacks=[cb]) 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")) content = f.read_text() assert "# RAW RESPONSE" in content, content assert "Who was Pedro Sanchez?" in content, content print(f"ok: raw response appended to {f.name}") 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__": test_parse_numbered_lines() test_parse_bare_number_lines_dropped() test_parse_enumerator_prefix() test_parse_happy_path_unchanged() test_init_degrades_to_original_question() test_empty_raw_stays_atomic() test_prompt_log_captures_raw_response() print("\nrobust_init tests passed")