Back to all articlesAI & Agents

Reflection Without Self-Delusion: Verification Loops That Stop (Part 7)

Verification before reflection

Decidable checkscitation, number, quote
Rubric criticscore drives arithmetic
Score penalty0.15 per open verdict
Three stop conditionsrounds, delta, oscillation

One reflection round

The program checks are a veto the critic cannot outvote.

One reflection round — flow diagramOne reflection round. Flow diagram with 6 steps. Shapes: pill = input, rounded rect = process, diamond = decision, double border = output, dashed = loop. Steps in order: Step 1, draft answer (input), from AgentLoop trace; Step 2, extract claims (process), sentence + [doc#n] citations; Step 3, programmatic checks (decision), no_citation / number_mismatch; Step 4, rubric critique (decision), score - 0.15 x errors; Step 5, revise from issues (process), clean citations kept; Step 6, labelled answer (output), stopped_by records why. Then loops back to step 3: ↺ repeat until accepted, no_progress, oscillation or max_rounds.draft answerfrom AgentLoop traceextract claimssentence + [doc#n] citationsprogrammaticchecksno_citation / number_mismatchrubric critiquescore - 0.15 x errorsrevise from issuesclean citations keptlabelled answerstopped_by records why
  • input
  • process
  • decision
  • output

The most common reflection implementation is one prompt: Review your answer for errors and improve it. It reliably produces a longer answer. Whether it produces a better one is a different question, because the model reviewing its own draft has no information the draft did not already contain. The critique restates the answer with more confident wording, the revision restates the critique, and you have paid two model calls to increase the token count.

Reflection helps under exactly two conditions: the critique is anchored to evidence the first pass did not use, or a program checks something the model cannot argue with. This part builds both — and then builds the part everyone skips, the stop conditions, because an unbounded reflection loop alternates between two versions of the same answer until the step budget dies.

The payoff for the last three parts is concrete here. Part 5 gave every search result a citation id; Part 6 gave every task a bounded result. Citation ids make verification decidable: either the cited passage exists and contains the number, or it does not. Without them, verification is an opinion, and opinions do not stop loops.

What you’ll build

A reflect.py module with four pieces:

  • extract_claims + EvidenceStore — splits an answer into sentences, and checks each against the evidence the run actually retrieved: citation existence, number match, verbatim quotes.
  • RubricCritic — one model call per round with a four-point rubric, structured output, and a hard rule: a malformed critique is an accept, never a revision.
  • ReflectionLoop — critique, revise, with three stop conditions: round limit, minimum score improvement, oscillation detection by critique fingerprint.
  • ReflectiveAgent — runs AgentLoop for the draft, rebuilds the evidence set from the trace, then verifies.

One small change to contracts.py makes all of this possible, and it is worth calling out before anything else:

# Part 2's AgentLoop recorded the decision and the outcome; Part 7 needs the payload too.
record.update({"tool": name, "ok": result.ok, "attempts": result.attempts,
"error_code": result.error_code, "from_cache": result.from_cache,
"data": result.data})

data: result.data is one line, and it is the difference between a trace you can only read and a trace you can verify against. Without it, the evidence set would have to be reconstructed from the model’s memory of what it read — which is exactly the failure reflection is supposed to catch.

Prerequisites

  • Parts 1–6. reflect.py imports AgentLoop, LLMClient, Message, Tool from contracts.py.
  • Python 3.10+, standard library only (re, json, hashlib).
  • The demo uses a stub search tool with two canned passages so it runs offline; in the real project, wire the Part 5 make_search_tool(retriever) — the reflection layer does not care which.

Why “reflect on your answer” makes things worse

The abstract self-critique fails for a structural reason, not a prompt-engineering one. The critique step is a second model call whose only input is text the first call produced. There is no new information, so the best possible critique is a re-derivation of what is already there — and models are notably bad at flagging their own confident errors, because the same weights that produced the sentence judge the sentence.

What reflection can use, and what this part wires up, is differential information:

  • The evidence set — what the tools actually returned, which the draft may have ignored or inverted.
  • Decidable checks — citation existence, number match, quote presence, which need no model at all.
  • A rubric with a scale — so score can drive arithmetic instead of vibes.

The order matters, and it is the core design: programmatic checks first, model judgement second. There is also an accountability asymmetry that is easy to miss. When a model-based critique is wrong, nothing in the system can say so — the critique is a judgement, and judgements do not leave an audit trail. When EvidenceStore.check flags number_mismatch, the verdict names the claim, the code, and the exact number that is absent from the named citation. A developer reading open_verdicts sees a falsifiable statement, which means a false positive is debuggable: check the passage, check the regex, fix the rule. Build the checkable layer first, and every later disagreement between the critic and the checks has a ground truth to appeal to. A check that runs in 40 microseconds either passes or names a defect; the critic then judges what a program cannot — whether the claim is responsive to the goal, whether the reasoning is coherent. Feeding the critic only prose and asking it to do both jobs gets you the worst of both: it cannot verify numbers reliably, and it will spend its attention on grammar.

Checks a program can run: citations, numbers, quotes

A claim is a sentence with zero or more citation ids. The checks are deliberately mechanical:

from __future__ import annotations
from dataclasses import dataclass, field
import hashlib
import json
import re
from contracts import AgentLoop, LLMClient, Message, Tool
CITATION = re.compile(r"\[([a-z][a-z0-9_-]{1,40}#\d+)\]")
NUMBER = re.compile(r"\d+(?:\.\d+)?")
QUOTE = re.compile(r'"([^"]{8,160})"')
SENTENCE = re.compile(r"(?<=[.!?])\s+")
@dataclass
class Evidence:
id: str
text: str
@dataclass
class Claim:
text: str
citations: tuple[str, ...]
@dataclass(frozen=True)
class Verdict:
claim: str
code: str # ok | no_citation | unknown_citation | number_mismatch | quote_missing
detail: str = ""
@property
def failed(self) -> bool:
return self.code != "ok"
def extract_claims(answer: str) -> list[Claim]:
return [
Claim(sentence, tuple(CITATION.findall(sentence)))
for sentence in (s.strip() for s in SENTENCE.split(answer.strip()))
if sentence
]
class EvidenceStore:
"""The evidence the run actually retrieved. Claims are checked against this, not against belief."""
def __init__(self, evidence: list[Evidence]) -> None:
self.items = {e.id: e for e in evidence}
def check(self, claim: Claim) -> list[Verdict]:
if not claim.citations:
return [Verdict(claim.text, "no_citation", "claim cites no evidence")]
verdicts: list[Verdict] = []
for citation in claim.citations:
item = self.items.get(citation)
if item is None:
verdicts.append(Verdict(claim.text, "unknown_citation",
citation + " was never retrieved"))
continue
missing_numbers = [n for n in NUMBER.findall(claim.text)
if n not in item.text]
if missing_numbers:
verdicts.append(Verdict(
claim.text, "number_mismatch",
",".join(missing_numbers) + " absent from " + citation))
missing_quotes = [q for q in QUOTE.findall(claim.text)
if not any(q in item.text for item in self.items.values())]
for quote in missing_quotes:
verdicts.append(Verdict(claim.text, "quote_missing", quote[:60]))
if not verdicts:
verdicts.append(Verdict(claim.text, "ok", ""))
return verdicts
def check_claims(self, claims: list[Claim]) -> list[Verdict]:
out: list[Verdict] = []
for claim in claims:
out.extend(self.check(claim))
return out
def block(self, max_chars: int = 1400) -> str:
lines: list[str] = []
for item in self.items.values():
lines.append("[%s] %s" % (item.id, item.text[:200]))
return "\n".join(lines)[:max_chars]

Four checks, each with a known blind spot that the design accepts rather than hides.

no_citation is the cheapest and the most valuable. An uncited claim is not necessarily wrong, but it is unverifiable, and in a research agent unverifiable is a defect: the whole point of Part 5’s citation format was to make claims checkable. Treat the absence as a failure and the model learns to cite — the prompt-side instruction (cite as [doc#n]) plus this check is a closed loop.

unknown_citation catches hallucinated citations — [retrieval-design#7] when that document has two chunks. This is the check that vector-database-RAG systems skip, and it is free.

number_mismatch is strict to the point of pedantry: every number in the claim must appear verbatim in the cited text. That means a legitimate paraphrase — the evidence says 180 to 240 milliseconds, the claim says about 200 ms — is flagged. This is intentional. A paraphrased number is the single most common way a correct retrieval becomes a wrong answer, and a flagged paraphrase costs one revision round, while an unflagged invented number costs a wrong deliverable. The 200 ms case is exactly what the demo below shows.

quote_missing only fires on quoted spans of 8–160 characters. Shorter spans are noise; longer ones are usually the model quoting its own summary. The check verifies the quote exists somewhere in the evidence — not that it is attributed to the right citation, which would need span alignment and is not worth the complexity at this stage.

A critic with a rubric, and one veto

The critic is one model call with a rubric, a scale, and structured output. The scale exists so the loop can do arithmetic on it.

CRITIC_SYSTEM = (
"You are a critic. Score the draft answer against the evidence. Rubric: "
"(1) every factual claim cites evidence; (2) numbers match the cited text exactly; "
"(3) no claim goes beyond what the evidence supports; (4) the answer responds to the goal. "
"Reply with JSON: {\"type\": \"critique\", \"score\": 0.0-1.0, \"verdict\": \"accept|revise\", "
"\"issues\": [{\"claim\": \"...\", \"problem\": \"...\", \"fix\": \"...\"}]}. "
"Score below 0.80 means revise."
)
@dataclass
class Critique:
score: float
verdict: str
issues: list[dict] = field(default_factory=list)
fingerprint: str = ""
class RubricCritic:
"""One model call per round. A malformed critique is an accept, never a revision."""
def __init__(self, llm: LLMClient) -> None:
self.llm = llm
def review(self, goal: str, draft: str, evidence_block: str) -> Critique:
decision = self.llm.complete(
[Message("system", CRITIC_SYSTEM),
Message("user", "Goal: %s\n\nEVIDENCE:\n%s\n\nDRAFT:\n%s" % (goal, evidence_block, draft))],
[],
)
try:
if decision.get("type") != "critique":
raise ValueError("expected a critique decision")
score = float(decision.get("score", 1.0))
verdict = str(decision.get("verdict", "accept"))
issues = decision.get("issues") or []
if verdict not in ("accept", "revise") or not 0.0 <= score <= 1.0:
raise ValueError("malformed critique")
except (TypeError, ValueError):
return Critique(1.0, "accept", [], "unparseable")
fingerprint = hashlib.sha256(
json.dumps([str(i.get("claim", i))[:120] for i in issues], sort_keys=True)
.encode("utf-8")).hexdigest()[:10]
return Critique(min(1.0, max(0.0, score)), verdict, issues, fingerprint)

Two policies in that class deserve their own sentences.

A malformed critique is an accept. This looks backwards — surely a broken critic means “try again”? It does not, because retrying the critic inside the loop creates an unbounded failure path: the critic fails, you retry, it fails differently, you retry. The safe reading of a critique you cannot parse is that you cannot act on it, and not acting means accepting the current draft, which has already passed the programmatic checks. The loop records critic_unparseable as its stop reason, so the run is labelled, not silent.

The fingerprint is the oscillation detector. Hashing the issue claims turns “the critic keeps saying the same thing” into an equality test. Without it, a critic that flags claim one is thin forever produces an infinite revise loop — and fingerprint equality is a stronger signal than score equality, because scores drift while a stuck issue does not.

Three stop conditions

The loop composes checks, critic, and revision. Its entire behaviour is in the ordering of three exit conditions:

@dataclass
class ReflectionConfig:
max_rounds: int = 2
min_delta: float = 0.08
accept_score: float = 0.8
@dataclass
class ReflectionRun:
final_answer: str
rounds: int
stopped_by: str # accepted | no_progress | oscillation | max_rounds | critic_unparseable
history: list[dict] = field(default_factory=list)
@property
def open_verdicts(self) -> list[Verdict]:
last = self.history[-1] if self.history else {}
return [v for v in last.get("verdicts", []) if v.failed]
class ReflectionLoop:
"""Critique, then revise, with three stop conditions. Never revises on a hunch."""
def __init__(self, llm: LLMClient, critic: RubricCritic, store: EvidenceStore,
config: ReflectionConfig | None = None) -> None:
self.llm = llm
self.critic = critic
self.store = store
self.config = config or ReflectionConfig()
def run(self, goal: str, draft: str) -> ReflectionRun:
current = draft
last_score: float | None = None
last_fingerprint: str | None = None
history: list[dict] = []
stopped_by = "max_rounds"
for round_index in range(self.config.max_rounds):
verdicts = self.store.check_claims(extract_claims(current))
errors = sum(1 for v in verdicts if v.failed)
critique = self.critic.review(goal, current, self.store.block())
if critique.fingerprint == "unparseable":
history.append({"round": round_index, "score": None, "verdicts": verdicts,
"stopped_by": "critic_unparseable"})
return ReflectionRun(current, round_index + 1, "critic_unparseable", history)
score = max(0.0, min(1.0, critique.score - 0.15 * errors))
entry = {"round": round_index, "score": round(score, 2),
"programmatic_errors": errors, "critique": critique,
"verdicts": verdicts}
history.append(entry)
if errors == 0 and critique.verdict == "accept" and score >= self.config.accept_score:
stopped_by = "accepted"
break
if last_score is not None and score - last_score < self.config.min_delta:
stopped_by = "no_progress"
break
if critique.fingerprint == last_fingerprint and critique.issues:
stopped_by = "oscillation"
break
last_score = score
last_fingerprint = critique.fingerprint
current = self.revise(goal, current, critique.issues)
return ReflectionRun(current, len(history), stopped_by, history)
def revise(self, goal: str, draft: str, issues: list[dict]) -> str:
bullets = []
for issue in issues[:5]:
bullets.append("- claim: %s\n problem: %s\n fix: %s"
% (issue.get("claim", ""), issue.get("problem", ""),
issue.get("fix", "")))
decision = self.llm.complete(
[Message("system", "Rewrite the answer to fix every issue. Keep citations that "
"verified clean. Change nothing else."),
Message("user", "Goal: %s\n\nDRAFT:\n%s\n\nISSUES:\n%s" % (goal, draft, "\n".join(bullets)))],
[],
)
return str(decision.get("content", "")) or draft

The penalty is the veto. score - 0.15 * errors subtracts directly, so a critic that scores an uncited, number-fabricated draft at 0.9 still lands at 0.6 — below accept_score, and the revision happens. The accept condition also requires errors == 0, so no arithmetic can rescue a run with open verdicts. This is what keeps the critic honest: the program checks are not advisory, they are a veto the critic cannot outvote.

min_delta=0.08 is the anti-dithering condition. Revision costs two calls (critique + revise, plus a critique to judge the revision). If the last revision moved the score by less than 0.08, the next one is unlikely to do better, and the honest answer is to stop and label: no_progress. In the tests below, a 0.55 → 0.60 round triggers exactly this.

Oscillation is checked after improvement, on purpose. A big score jump with an identical fingerprint is suspicious — the critic liked the rewrite and repeated the same complaint. Stopping there beats a third round, because the third round can only replay the second. The order of the three checks is: accept, then improvement, then fingerprint. Reorder them and you get different failure runs; the tests pin the order.

max_rounds=2 is the budget, and the default answer. The loop exits with stopped_by="max_rounds" and the current draft, which after two revisions is usually better than the original even if it never reached accept_score. Shipping it with a label is better than discarding it — the caller (Part 8’s checkpoint layer) can decide whether a max_rounds answer is acceptable for its use case.

Wiring it into the run

The agent rebuilds evidence from the trace, so verification is anchored to what the tools returned, not what the model remembers:

def evidence_from_trace(trace: list[dict]) -> list[Evidence]:
"""Rebuild the evidence set from a run's search calls. Requires trace records with data."""
items: dict[str, Evidence] = {}
for record in trace:
if record.get("tool") != "search" or not record.get("ok"):
continue
try:
for hit in json.loads(record.get("data", "[]")):
items[hit["citation"]] = Evidence(hit["citation"], hit["text"])
except (ValueError, KeyError, TypeError):
continue
return list(items.values())
class ReflectiveAgent:
"""AgentLoop for the draft, then verification. Evidence comes from the trace, not memory."""
def __init__(self, llm: LLMClient, tools: list[Tool], config: ReflectionConfig | None = None,
max_steps: int = 6, critic: RubricCritic | None = None) -> None:
self.llm = llm
self.tools = tools
self.config = config or ReflectionConfig()
self.max_steps = max_steps
self.critic = critic or RubricCritic(llm)
self.last_trace: list[dict] = []
def run(self, goal: str) -> ReflectionRun:
loop = AgentLoop(self.llm, self.tools, max_steps=self.max_steps)
draft = loop.run(goal)
self.last_trace = loop.trace
store = EvidenceStore(evidence_from_trace(loop.trace))
return ReflectionLoop(self.llm, self.critic, store, self.config).run(goal, draft)

evidence_from_trace skips failed searches (not record.get("ok")) — evidence the tool never produced cannot verify anything, and a draft citing a failed search’s citation is caught by unknown_citation instead.

Three properties of that rebuild matter more than they look.

Deduplication is automatic. A run that issues five searches will retrieve overlapping passages — the Part 5 index overlaps chunks by design, and two queries often surface the same citation. items is keyed by citation id, so the evidence set is the union of unique passages, not five copies of the same three chunks. The verification cost is therefore bounded by corpus diversity, not by run length.

The evidence block is a budget decision. block() caps at 1,400 characters — about 350 tokens — with each passage truncated at 200. Two searches returning four passages each therefore cost at most 350 tokens per critique call, and with max_rounds=2 that is 700 tokens of critique context for the whole run. Compare the naive alternative, pasting the full trace into the critic: five searches at 420 tokens each is 2,100 tokens, and the critic reads tool output the draft may never have used.

max_steps=6 bounds the draft, not the verification. A draft produced after six loop steps can cite at most six search payloads, so the evidence set has a hard ceiling of six distinct citation clusters. That is why verification cost scales with max_steps even though the loop config never mentions it — and why Part 8 will persist the trace alongside the checkpoint rather than recomputing it.

The demo catches the exact failure this part exists for. The draft states 340 ms; the evidence says about 200 ms:

import json
import reflect as rf
from contracts import ScriptedLLM, Tool, ToolResult
EVIDENCE = [
rf.Evidence("latency-budget#0",
"Reranking 20 candidates costs about 200 ms per query at 12 layers. "
"Capping the set at 8 candidates brings the added cost under 100 ms."),
rf.Evidence("chunking#0",
"Chunk sizes between 300 and 500 characters with a fifth of the window "
"as overlap balance precision against index inflation."),
]
DRAFT = ("A cross-encoder reranker costs about 340 ms per query for 20 candidates "
"[latency-budget#0]. Chunk windows should sit between 300 and 500 characters "
"[chunking#0].")
REVISED = ("A cross-encoder reranker costs about 200 ms per query for 20 candidates "
"[latency-budget#0]. Chunk windows should sit between 300 and 500 characters "
"[chunking#0].")
def stub_search_tool() -> Tool:
passages = [
{"citation": "latency-budget#0", "doc": "latency-budget", "text": EVIDENCE[0].text, "score": 0.8},
{"citation": "chunking#0", "doc": "chunking", "text": EVIDENCE[1].text, "score": 0.6},
]
def _run(args: dict) -> ToolResult:
return ToolResult(ok=True, data=json.dumps(passages))
return Tool(
name="search",
description="Return two canned passages with citations.",
parameters={
"type": "object",
"properties": {"query": {"type": "string", "minLength": 2}},
"required": ["query"],
"additionalProperties": False,
},
_fn=_run,
)
def critique(score, verdict, claims):
return {"type": "critique", "score": score, "verdict": verdict,
"issues": [{"claim": c, "problem": "unsupported", "fix": "cite evidence"}
for c in claims]}
SCRIPT = [
{"type": "tool", "name": "search", "arguments": {"query": "reranker latency"}},
{"type": "final", "content": DRAFT},
critique(0.62, "revise", ("A cross-encoder reranker costs about 340 ms per query",)),
{"type": "final", "content": REVISED},
critique(0.90, "accept", ()),
]
def demo() -> None:
llm = ScriptedLLM(SCRIPT)
agent = rf.ReflectiveAgent(llm, [stub_search_tool()], max_steps=3)
run = agent.run("What does reranking cost in latency?")
for entry in run.history:
bad = [(v.code, v.detail) for v in entry.get("verdicts", []) if v.failed]
print("round %d score=%s programmatic_errors=%s open=%s"
% (entry["round"], entry.get("score"), entry.get("programmatic_errors", 0), bad))
print("stopped_by:", run.stopped_by, "rounds:", run.rounds, "model calls:", len(llm.calls))
print("final:", run.final_answer)
if __name__ == "__main__":
demo()
round 0 score=0.47 programmatic_errors=1 open=[('number_mismatch', '340 absent from latency-budget#0')]
round 1 score=0.9 programmatic_errors=0 open=[]
stopped_by: accepted rounds: 2 model calls: 5
final: A cross-encoder reranker costs about 200 ms per query for 20 candidates [latency-budget#0]. Chunk windows should sit between 300 and 500 characters [chunking#0].

Read the costs, because they are the reason max_rounds is 2 and not 5. The baseline run is 2 model calls (search, final). Reflection adds 3: one critique, one revision, one critique. That is 2.5× the calls and roughly 2× the tokens — the critique and revision prompts both carry the evidence block (≤1,400 characters) plus the draft. One round caught one fabricated number. That is a good trade. Five rounds to polish a correct answer is not, which is precisely what no_progress and oscillation exist to prevent.

Also notice what the critic did not have to do: it never saw 340 as a problem of arithmetic. The programmatic check found it, named it (340 absent from latency-budget#0), and the critic’s job collapsed to judgement — is the rest of the draft acceptable? That division of labour is why one revision round was enough.

Failure modes and how to handle them

Failure What actually happens Handling here Still broken
Legitimate paraphrase of a number about 200 ms vs 180 to 240 milliseconds Flagged, costs one revision round No range-aware number check
Critic scores everything 0.95 Reflection never triggers Penalty + errors == 0 accept condition A calibrated critic needs real data (Part 10)
Critic output unparseable Loop would crash or spin critic_unparseable stop, draft returned No retry — a persistently broken critic is an incident
Same issue every round Infinite revision Fingerprint equality → oscillation Fix suggests are not applied by the reviser
Evidence set empty (no search ran) Every claim uncited no_citation on all claims No distinction between “no evidence needed” and “evidence skipped”
Draft cites a failed search Citation never retrieved unknown_citation The model may retry search and drift
Revision breaks a clean claim Score drops after revision no_progress stops the loop Revision prompt says keep citations, cannot enforce

The first row is the honest cost of strict checks: number_mismatch fires on paraphrase. If your corpus is full of ranges and approximations, either accept one extra revision round per answer, or relax the check to numeric-tolerance comparison — parse both numbers, flag only if they differ by more than 10 percent. The second option is a ten-line change to check and a good exercise, but note what it gives up: about 200 matching a 180 to 240 range is a judgement, and once the check makes judgements it can be argued with.

Trade-offs

Decision Alternative Why we chose it Cost
Programmatic checks first Critic judges everything Decidable, free, cannot be argued with Paraphrased numbers flagged
Malformed critique = accept Retry the critic No unbounded failure path A flaky critic silently accepts
max_rounds=2 5 or unlimited Cost is linear in rounds Harder problems stop early, labelled
Penalty arithmetic (0.15 × errors) Critic sees verdicts as text Critic cannot outvote the checks Weight is a magic number until Part 10
Fingerprint of issue claims Hash the full critique Robust to reordering and score drift Same claim with different wording slips through
Evidence from trace Ask the model to attach evidence Trace is ground truth Needs data in trace records
Revise from issues, not scratch Regenerate the answer Preserves verified claims Inherits draft structure

The penalty row is the one to revisit with data. 0.15 means one programmatic error costs 15 score points, which is a calibration guess, not a measurement. Part 10’s harness will replace it: run the agent over a labelled set, count answers accepted with open verdicts, and set the weight so that number is zero.

Testing it

Thirteen tests, no network, 7 ms. The invariants:

import json
import unittest
import reflect as rf
from contracts import ScriptedLLM, Tool, ToolResult
EVIDENCE = [
rf.Evidence("latency-budget#0",
"Reranking 20 candidates costs about 200 ms per query at 12 layers. "
"Capping the set at 8 candidates brings the added cost under 100 ms."),
rf.Evidence("chunking#0",
"Chunk sizes between 300 and 500 characters with a fifth of the window "
"as overlap balance precision against index inflation."),
]
def store():
return rf.EvidenceStore(EVIDENCE)
def critique(score, verdict, claims):
return {"type": "critique", "score": score, "verdict": verdict,
"issues": [{"claim": c, "problem": "unsupported", "fix": "cite evidence"}
for c in claims]}
class TestChecks(unittest.TestCase):
def test_uncited_claim_is_flagged(self):
verdicts = store().check(rf.Claim("Reranking costs 200 ms per query.", ()))
self.assertEqual(verdicts[0].code, "no_citation")
def test_invented_citation_is_flagged(self):
verdicts = store().check(rf.Claim("Reranking is slow [ghost-doc#0].", ("ghost-doc#0",)))
self.assertEqual(verdicts[0].code, "unknown_citation")
def test_fabricated_number_is_flagged(self):
claim = rf.Claim("Reranking costs about 340 ms per query [latency-budget#0].",
("latency-budget#0",))
verdicts = store().check(claim)
self.assertEqual(verdicts[0].code, "number_mismatch")
self.assertIn("340", verdicts[0].detail)
def test_unsupported_quote_is_flagged(self):
claim = rf.Claim('The guide says "never rerank above twelve candidates" [latency-budget#0].',
("latency-budget#0",))
self.assertEqual(store().check(claim)[0].code, "quote_missing")
def stub_search_tool() -> Tool:
passages = [
{"citation": "latency-budget#0", "doc": "latency-budget", "text": EVIDENCE[0].text, "score": 0.8},
{"citation": "chunking#0", "doc": "chunking", "text": EVIDENCE[1].text, "score": 0.6},
]
def _run(args: dict) -> ToolResult:
return ToolResult(ok=True, data=json.dumps(passages))
return Tool(name="search", description="Canned passages.",
parameters={"type": "object",
"properties": {"query": {"type": "string", "minLength": 2}},
"required": ["query"], "additionalProperties": False},
_fn=_run)
DRAFT = ("A cross-encoder reranker costs about 340 ms per query for 20 candidates "
"[latency-budget#0]. Chunk windows should sit between 300 and 500 characters [chunking#0].")
REVISED = ("A cross-encoder reranker costs about 200 ms per query for 20 candidates "
"[latency-budget#0]. Chunk windows should sit between 300 and 500 characters [chunking#0].")
class TestLoop(unittest.TestCase):
def test_fabricated_number_survives_one_revision_then_accepts(self):
llm = ScriptedLLM([
{"type": "tool", "name": "search", "arguments": {"query": "reranker latency"}},
{"type": "final", "content": DRAFT},
critique(0.62, "revise", ("A cross-encoder reranker costs about 340 ms",)),
{"type": "final", "content": REVISED},
critique(0.90, "accept", ()),
])
run = rf.ReflectiveAgent(llm, [stub_search_tool()]).run("What does reranking cost?")
self.assertEqual(run.rounds, 2)
self.assertEqual(run.stopped_by, "accepted")
self.assertEqual(run.history[0]["programmatic_errors"], 1)
self.assertIn("340", run.history[0]["verdicts"][0].detail)
def test_same_issue_twice_is_oscillation(self):
llm = ScriptedLLM([
critique(0.55, "revise", ("claim one is thin",)),
{"type": "final", "content": "Claim one, expanded [latency-budget#0]."},
critique(0.75, "revise", ("claim one is thin",)),
])
run = rf.ReflectionLoop(llm, rf.RubricCritic(llm), store(),
rf.ReflectionConfig(max_rounds=4, min_delta=0.01)
).run("goal", "Claim one [latency-budget#0].")
self.assertEqual(run.stopped_by, "oscillation")
def test_no_progress_stops_before_a_second_revision(self):
llm = ScriptedLLM([
critique(0.55, "revise", ("claim one is thin",)),
{"type": "final", "content": "Claim one, expanded [latency-budget#0]."},
critique(0.60, "revise", ("claim one is still thin",)),
])
run = rf.ReflectionLoop(llm, rf.RubricCritic(llm), store(),
rf.ReflectionConfig(max_rounds=4)).run(
"goal", "Claim one [latency-budget#0].")
self.assertEqual(run.stopped_by, "no_progress")
self.assertEqual(len(run.history), 2)
def test_unparseable_critic_never_forces_a_revision(self):
llm = ScriptedLLM([{"type": "critique", "score": "high", "verdict": "maybe"}])
run = rf.ReflectionLoop(llm, rf.RubricCritic(llm), store(),
rf.ReflectionConfig(max_rounds=3)).run("g", "draft")
self.assertEqual(run.stopped_by, "critic_unparseable")
self.assertEqual(run.final_answer, "draft")
def test_reviser_prompt_contains_the_issues(self):
llm = ScriptedLLM([
critique(0.55, "revise", ("claim one is thin",)),
{"type": "final", "content": "Claim one, fixed [latency-budget#0]."},
critique(0.95, "accept", ()),
])
rf.ReflectionLoop(llm, rf.RubricCritic(llm), store()).run("g", "Claim one [latency-budget#0].")
self.assertIn("claim one is thin", llm.calls[1][1].content)
if __name__ == "__main__":
unittest.main()

test_no_progress_stops_before_a_second_revision and test_same_issue_twice_is_oscillation are deliberately near-identical — same critique shape, same draft — because the two stop conditions must be distinguishable by score movement, not by test setup. If a refactor merges them into one check, these two tests fail with different stopped_by values and the merge is visible.

test_unparseable_critic_never_forces_a_revision pins the accept-on-malformed policy. The tempting alternative — retry the critic — is exactly the unbounded path, and this test is the guardrail.

Exercises

  1. Tolerant number checking. Change number_mismatch to parse both claim and evidence numbers and flag only differences above 10 percent. Then write the adversarial case: the evidence says under 100 ms, the draft claims 95 ms. Does tolerance let a wrong precise number through? Where is the line?
  2. Per-check penalties. Replace 0.15 * errors with a weight per code: unknown_citation should cost more than quote_missing. Justify each weight in one sentence, then run ten drafts through the loop and report whether the accept rate changed.
  3. Reflect inside a task. Give PlannedAgent._run_task a reflection pass: verify each task result against its own search evidence before returning it. Measure total model calls and wall time for the four-task plan with and without per-task reflection. Where does per-task verification beat end-of-run verification, and where is it wasted?

Exercise 3 is the architectural one. Verification at the task boundary catches errors before they enter the synthesis, but pays the reflection cost on every task — the measurement decides, and it is the first time this series has had to choose where a quality mechanism lives.

What’s next

Everything so far runs inside one process: the trace, the plan, the evidence set, and the reflection history all disappear when it does. A run that takes four minutes cannot survive a deploy, and a crash on task 6 of 8 restarts from task 1.

Part 8, Checkpointing and recovery, adds durable state: a checkpoint written after every task and every loop step, idempotent tool replay so a resumed run never repeats a side effect, and resume-from-checkpoint semantics for the planner. The reflection history you just built becomes part of the checkpoint — a resumed run should not re-critique an answer that already passed.

Connect your agents without writing code

Everything above, running in Ball — no code, no install. Try it in your browser.

Try Ball free
Get the free AI agent kit

Only used to send Ball resources. No spam.

Try Ball in your browser — no install, no signup needed.

Try Ball in your browser — no install, no signup needed.

Reading in English? Switch language in the menu.