Files
floop/code/tests/reask_meter.py
T
onibot efd539c128 knowledge+llm: dst-first ablation mask (run L) + re-ask budget meter
Two fixes from his 22/10 re-run log, both small and deterministic:

1. THE ABLATION MASK WAS QUOTE-BLINDED (run L: Q1 stayed silent over
   the Pedro page that run J flags). The Pedro paragraph interleaves
   all three readings in ONE quote ('...Secretary-General ... ninth
   president of Socialist International...'), and _carries matched
   the picked value by substring over dst OR quote — so masking SI's
   support masked the PM/PSOE rows too; round 1 answered UNKNOWN and
   the audit died silent. The DST-FIRST LAW: when a row has a
   meaningful dst (non-empty, non-numeric) it is the VALUE BEARER and
   the mask matches IT; the quote is a fallback only for
   empty/numeric dsts. Same law in _carries_target for each round's
   surviving value, with one addition: the judge's round value may be
   an OFFICE DESCRIPTION ('prime minister of Spain') while the row's
   dst is the ENTITY ('Spain') — resolve by reciprocal token
   containment, or the loop dies after one alternative.

2. THE ADAPTER RE-ASK WAS INVISIBLE TO THE BUDGET (run L: prompts #9
   and #10 were both ANSWER — #10 5 chars shorter, 340s, the
   ChatAdapter's JSON-fallback second wire call after a parse
   failure; llm_calls said 9/80 while 10 hit the wire). THE METER:
   the prompt-log callback already sees every LM call — a second LM
   call with NO new module forward between them is the adapter
   fallback re-firing inside the same Predict. Count it, log the
   line, and charge the budget through a meter hook the machine
   wires at construction. A re-ask at the ceiling does not kill the
   run (the call already happened). dspy's BEHAVIOUR IS UNTOUCHED —
   his call: the fallback stays, it is future self-improvement
   signal (which prompts the model formats badly), not a bug.

Tests: knowledge/tests/ablation.py +3 — run-L regression (interleaved
one-paragraph quote flags all three readings), office-description
resolution, numeric-dst quote fallback. tests/reask_meter.py +3 —
fallback detected and charged on the REAL adapter path (custom engine
returning raw text, marker-less first response), separate forwards NOT
flagged (the ablation-rounds shape), ceiling charge survives. Suite
12/12 files green (74 tests). Live smokes: the run-L interleaved-quote
page flags SI+PM+SG through the full pipeline; the run-J
separate-quotes smoke still passes.
2026-10-22 11:21:25 +02:00

142 lines
4.8 KiB
Python

"""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()