"""Re-ask meter tests (run L): dspy's adapter JSON fallback fires a second LM call inside the SAME module forward — the budget never charged it (9/80 logged, 10 on the wire, the extra burning 340s of GPU). Laws under test: 1. The meter DETECTS the fallback (marker-less first response) and charges the budget once via the hook; dspy's behaviour is untouched (the second call still runs — his call: the fallback stays, it is future self-improvement signal). 2. Separate forwards (the ablation rounds) are NOT re-asks. 3. A re-ask at budget ceiling does not kill the run (the call already happened — note only). The repro drives dspy's REAL adapter path: a custom engine returning raw text (exactly what the OpenAI-compatible endpoint returns), first response WITHOUT the '[[ ## field ## ]]' marker -> ChatAdapter raises AdapterParseError -> JSONAdapter fallback re-fires the call. Run: .venv/bin/python tests/reask_meter.py """ from __future__ import annotations import sys import tempfile import warnings from pathlib import Path warnings.filterwarnings("ignore") sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) import dspy from dspy._vendor.lm15 import Response, TextPart, Message, Usage from floop.llm import PromptLogCallback from floop.stream import RunStreams from floop.state import Budget, BudgetExhausted class AnswerSig(dspy.Signature): goal: str = dspy.InputField() final_answer: str = dspy.OutputField() def _resp(text: str) -> Response: return Response( id="x", model="fake", message=Message(role="assistant", parts=(TextPart(text=text),)), finish_reason="stop", usage=Usage(input_tokens=1, output_tokens=1)) class FallbackEngine: """First response lacks the output-field marker: the ChatAdapter parse fails and the JSON-adapter fallback re-fires the call (run-L shape).""" def __init__(self): self.i = 0 self.responses = [ "L'anterior president del Govern d'Espanya va ser Mariano Rajoy.", '{"final_answer": "Mariano Rajoy (JSON retry)"}', ] def complete(self, request, **kw): i = min(self.i, len(self.responses) - 1) self.i += 1 return _resp(self.responses[i]) class CleanEngine: """Every forward parses cleanly — two separate module forwards, no fallback (the ablation-rounds shape: same stage, fresh forwards).""" def __init__(self): self.i = 0 def complete(self, request, **kw): self.i += 1 return _resp(f"[[ ## final_answer ## ]]\nreading {self.i}") def test_fallback_detected_and_charged(): streams = RunStreams("meter test", verbose=False, runs_dir=tempfile.mkdtemp()) cb = PromptLogCallback(streams) dspy.configure(lm=dspy.LM(model="fake", engine=FallbackEngine()), callbacks=[cb]) charged = [] cb.meter = lambda stage: charged.append(stage) out = dspy.Predict(AnswerSig)(goal="who?") files = list((streams.run_dir / "prompts").glob("*.txt")) assert len(files) == 2, f"two wire calls expected: {[f.name for f in files]}" assert cb.reasks == 1, cb.reasks assert charged == ["AnswerSig"], charged assert "JSON retry" in out.final_answer, "dspy behaviour untouched" print("ok: adapter fallback detected — 2 wire calls, 1 re-ask, 1 charge") def test_separate_forwards_not_flagged(): streams = RunStreams("rounds test", verbose=False, runs_dir=tempfile.mkdtemp()) cb = PromptLogCallback(streams) charged = [] cb.meter = lambda stage: charged.append(stage) dspy.configure(lm=dspy.LM(model="fake2", engine=CleanEngine()), callbacks=[cb]) p = dspy.Predict(AnswerSig) p(goal="q1") p(goal="q2") # second forward: fresh module start, NOT a re-ask assert cb.reasks == 0, f"separate forwards flagged: {cb.reasks}" assert charged == [] print("ok: two separate forwards (ablation rounds) NOT flagged") def test_meter_never_kills_run(): """The meter hook raising (budget ceiling) must not kill the run — the wire call already happened.""" from floop.machine import FloopRun b = Budget(max_llm_calls=1, max_depth=1, max_retries=1, missing_extensions=1, min_child_budget=1) # simulate: budget at ceiling, meter fires class FakeModules: pass fm = FloopRun.__new__(FloopRun) fm.budget = b fm.notes = [] fm.streams = None fm._meter_reask("ANSWER") assert fm.budget.llm_calls == 1, "ceiling charge must not overflow the count" assert any("re-ask charged" in n for n in fm.notes), fm.notes print("ok: meter at ceiling — charged honestly, run survives") def main(): test_fallback_detected_and_charged() test_separate_forwards_not_flagged() test_meter_never_kills_run() print("\nre-ask meter tests passed") if __name__ == "__main__": main()