From b5a9403063bfde4212bcad634bac7ef0a1e42c65 Mon Sep 17 00:00:00 2001 From: Onibot Date: Wed, 21 Oct 2026 12:08:50 +0200 Subject: [PATCH] machine: robust INIT parsing + raw-response log (run I fixes) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Run I ('Who was the President before Pedro Sanchez?'): the INIT LM wrote its own line numbers as an extra first pipe field ('1 | Who was... | none | OPEN'), the naive parse took '1' as the subquestion text, ROUTE classified Q1='1' as numeric, and the machine burned four calls on garbage before luck produced the answer. Two of the fixes close the same observability gap that hid the root cause for a day. 1. PARSER (parse_subquestions): shifts the numbered form (>=4 fields with a bare number first) and drops any text that is a bare number — a routable question is text, never '1'. Enumerator prefixes ('1.') inside the text field are stripped. Well-formed lines parse exactly as before (regression-tested). 2. INIT DEGRADE (machine): init_decompose now returns (subs, raw). Non-empty raw that parses to nothing = model garbage — degrade to the ORIGINAL question as one OPEN subquestion (routable, logged, budget-safe). Empty raw keeps the old law: the question is atomic, stop and synthesize — never fabricate a subquestion. 3. RAW RESPONSE LOG (the ask behind the ask): prompts/NN-stage.txt now carries the exact LM response after the prompt. Run I's parsed 'OUTPUT INIT: 1\n2' could not show what the model actually wrote — the raw text is in the file from now on; the log stays line-based. Tests: tests/robust_init.py — the numbered form, bare-number drop, enumerator strip, happy-path regression, the degrade, the atomic stop, raw-response capture. Suite 59/59. Smoke: the exact run-I transcript replayed through the real machine (DummyLM) parses to Q1/Q2 real subquestions and answers Mariano Rajoy. --- code/floop/dspy_modules.py | 37 ++++++-- code/floop/llm.py | 19 +++- code/floop/machine.py | 16 +++- code/tests/machine.py | 2 +- code/tests/robust_init.py | 173 +++++++++++++++++++++++++++++++++++++ 5 files changed, 237 insertions(+), 10 deletions(-) create mode 100644 code/tests/robust_init.py diff --git a/code/floop/dspy_modules.py b/code/floop/dspy_modules.py index 1876505..98f88ee 100644 --- a/code/floop/dspy_modules.py +++ b/code/floop/dspy_modules.py @@ -6,6 +6,8 @@ Every module's docstring is the draft prompt — kept minimal on purpose. """ from __future__ import annotations +import re + import dspy from .state import AnswerType @@ -84,9 +86,13 @@ class FloopModules: self.missing = dspy.Predict(MissingSignature) self.answer = dspy.Predict(AnswerSignature) - def init_decompose(self, question: str) -> list[dict]: + def init_decompose(self, question: str) -> tuple[list[dict], str]: + """(parsed subquestions, raw model output). The machine decides what + an empty parse means: empty raw = the question is atomic; non-empty + raw that parses to nothing = model garbage (run I) — degrade.""" pred = self.init(question=question) - return parse_subquestions(pred.subquestions) + raw = pred.subquestions or "" + return parse_subquestions(raw), raw def missing_decompose(self, goal: str, evidence: str) -> list[dict]: pred = self.missing(goal=goal, evidence=evidence) @@ -111,17 +117,36 @@ class FloopModules: return pred.final_answer.strip() +_LINE_NO = re.compile(r"\d{1,2}[.)]?") +_ENUM = re.compile(r"^\d{1,2}[.)]?\s*[-–:]?\s+") + + +def _clean_qtext(t: str) -> str: + """Strip a leading enumerator ('1.', '2)', '3 -') from a subquestion.""" + return _ENUM.sub("", t.strip()).strip() + + def parse_subquestions(raw: str) -> list[dict]: - """>> parse the piped lines from INIT/MISSING: text | deps | answer_type.""" + """>> parse the piped lines from INIT/MISSING: text | deps | answer_type. + + The piped format is the contract; models still decorate it (run I): + qwen wrote its own line numbers as an extra first pipe field + ('1 | Who was the President before Pedro Sanchez? | none | OPEN') and + the naive parse took '1' as the text — Q1 routed as 'numeric' on the + literal question '1'. The parser now shifts the numbered form and + drops any field that is a bare number: a routable question is text.""" out: list[dict] = [] for line in (raw or "").strip().splitlines(): line = line.strip().lstrip("-•* ").strip() if not line or "|" not in line: continue parts = [p.strip() for p in line.split("|")] - text = parts[0] - if not text: - continue + # qwen's line-number prefix: an extra first field, bare number + if len(parts) >= 4 and _LINE_NO.fullmatch(parts[0]): + parts = parts[1:] + text = _clean_qtext(parts[0]) + if not text or _LINE_NO.fullmatch(text): + continue # a number is a line number, never a question deps_raw = parts[1].lower() if len(parts) > 1 else "none" atype_raw = parts[2].upper() if len(parts) > 2 else "OPEN" deps: list = [] diff --git a/code/floop/llm.py b/code/floop/llm.py index 140dc0e..8968362 100644 --- a/code/floop/llm.py +++ b/code/floop/llm.py @@ -49,6 +49,7 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback): self._stack: list[str] = [] # nested module stages (innermost last) self._starts: dict[str, float] = {} # lm call_id -> monotonic start self._stage_of: dict[str, str] = {} # lm call_id -> stage label + self._file_of: dict[str, Path] = {} # lm call_id -> prompt file # -- dspy plumbing ------------------------------------------------------- @@ -78,11 +79,13 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback): fn = f"{n:02d}-{label}.txt" pdir = streams.run_dir / "prompts" pdir.mkdir(exist_ok=True) - (pdir / fn).write_text( + f = pdir / fn + f.write_text( f"# stage={label} call_seq={n} chars={chars} " f"tokens~{chars // 4}\n\n" + text, encoding="utf-8", ) + self._file_of[call_id] = f streams.log( f"prompt #{n} stage={label} chars={chars} tokens~{chars // 4} " f"-> prompts/{fn}" @@ -95,7 +98,21 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback): streams = self.streams label = self._stage_of.pop(call_id, "lm") start = self._starts.pop(call_id, None) + f = self._file_of.pop(call_id, None) dur = f"{time.monotonic() - start:.1f}s" if start is not None else "?" + # RAW RESPONSE into the same file: the exact LM text, unmodified — + # the parsed OUTPUT can lie by omission (run I) + if f is not None: + raw = "" + if isinstance(outputs, list): + raw = "\n".join(str(o) for o in outputs) + elif outputs is not None: + raw = str(outputs) + with f.open("a", encoding="utf-8") as fh: + fh.write( + f"\n\n# RAW RESPONSE (after {dur}" + + (f", exception={exception!r}" if exception else "") + + ")\n" + (raw or "(empty)")) if streams is not None: streams.log(f"prompt {label} done in {dur}") diff --git a/code/floop/machine.py b/code/floop/machine.py index d4fe4c5..91de0b5 100644 --- a/code/floop/machine.py +++ b/code/floop/machine.py @@ -134,8 +134,20 @@ class FloopRun: self._charge() self.streams.call("INIT", f"decompose: {self.query[:80]}", think=self.tprefix + f"decomposing: {self.query[:100]}") - subs = self.modules.init_decompose(self.query) - self.streams.output("INIT", chr(10).join(s["text"] for s in subs) or "(no subquestions)") + subs, raw = self.modules.init_decompose(self.query) + if not subs and (raw or "").strip(): + # DEGRADE (run I): the model WROTE subquestions but none parsed + # (its numbered format beat the parser) — route the ORIGINAL + # question as one OPEN subquestion instead of routing garbage + # like a bare '1'. Deterministic, logged, budget-safe. The + # atomic case (empty raw) keeps the old stop-and-synthesize. + self.streams.output( + "INIT", f"(no parseable subquestions from {len(raw)} chars " + f"— degrading to the original question)", think=True) + subs = [{"text": self.query, "deps": [], + "answer_type": AnswerType.OPEN}] + else: + self.streams.output("INIT", chr(10).join(s["text"] for s in subs) or "(no subquestions)") self._add_questions(subs, reason="init") def _missing_round(self) -> None: diff --git a/code/tests/machine.py b/code/tests/machine.py index 955044f..ee596ab 100644 --- a/code/tests/machine.py +++ b/code/tests/machine.py @@ -31,7 +31,7 @@ class FakeModules: def init_decompose(self, question): self.calls.append(f"init:{question[:30]}") - return list(self.init_subs) + return list(self.init_subs), "" # (subs, raw) — atomic when empty def missing_decompose(self, goal, evidence): self.calls.append("missing") diff --git a/code/tests/robust_init.py b/code/tests/robust_init.py new file mode 100644 index 0000000..26a49d3 --- /dev/null +++ b/code/tests/robust_init.py @@ -0,0 +1,173 @@ +"""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") -- 2.55.0