Review the prerequisites
Suitable for: Backend developers learning Agent applications.
- Control and completion criteria in agent loops
- Model output proposes the next step; the runtime owns execution and terminal state. Stopping only establishes that the loop ended. Success additionally requires evidence that the agreed business conditions hold. Budget exhaustion, cancellation, and unknown outcomes therefore need distinct labels rather than one generic 'completed' state.
How does the mechanism work?
Step-by-step explanation
- One model round generates five tool calls, how to budget?
One round can contain multiple actions, so account for the abstract loop in the resource ledger.
- When the user cancels, the remote write operation has been successful. How do you end it?
Cancellation signals affect execution; business effects that already occurred require separate follow-through.
- Is a correct answer successful if the model did not run the required tests?
The terminal state must be determined by acceptance conditions, rather than how credible the text sounds.
Debugging · Diagnose failures
Debug · Reproduce a budget reset across invocations
Objectives of this level: Use emitted events and a failing contract to locate a persisted-budget regression, then repair only an isolated source copy.
Visual guide · Model stop and business finish
Only a bound merchant receipt completes the application. Approval, a final model answer and a timeout each establish different facts. Select the figure to open it at full size.
Failure evidence and exact starting state
Visual guide · Counters survive every resume
These are the disclosed read-only repair observations. They count committed tools, not all HTTP attempts, billed tokens or external writes. Select the figure to open it at full size.
A loop can appear bounded within every invocation while accumulating unlimited calls across invocations. Reproduce that error without touching work/agent.sqlite. Start in the extracted capstone directory; Python and local loopback service execution must already work as in its README. The script copies the Python files and migrations into a temporary directory and creates a fresh pair of databases for each check.
The contract stub always proposes the same authorized get_order arguments but gives each candidate a fresh call ID derived from the transcript. Fresh IDs are intentional: duplicate-call detection would otherwise mask the budget defect. There is no live model request, approval or merchant business write. The injected line resets both lifetime counters at the beginning of every run, before the first lease claim. Three invocations each permit three rounds.
# Run from the extracted capstone directory. Only a temporary copy is changed.
import json
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
root = Path.cwd()
box = Path(tempfile.mkdtemp(prefix="loop-boundary-"))
for path in root.glob("*.py"):
shutil.copy2(path, box / path.name)
shutil.copytree(root / "migrations", box / "migrations")
source = (box / "agent.py").read_text()
anchor = " lease = self.store.claim(task_id, lease_seconds)"
assert source.count(anchor) == 2
# Inject only into run(), before the first lease claim; execute() stays unchanged.
bug = " self.store.update(task_id, turn_count=0, tool_count=0) # BUG_RESET_BUDGET\n"
(box / "agent.py").write_text(source.replace(anchor, bug + anchor, 1))
check = r'''
import json
import tempfile
from pathlib import Path
from agent import Agent
from common import LabError
from harness import client, merchant_process
from store import Store
class RepeatOrder:
name = "repeated-read-contract-stub"
def respond(self, request):
n = sum(i.get("type") == "function_call" for i in request["input"]) + 1
call = {"type": "function_call", "call_id": "repeat-" + str(n),
"name": "get_order", "arguments": '{"order_id":"o-100"}'}
return {"status": "completed", "output": [call]}, {"source": "contract_stub"}
with tempfile.TemporaryDirectory(prefix="loop-check-") as tmp:
work = Path(tmp)
with merchant_process(work) as service:
store = Store(work / "agent.sqlite")
try:
agent = Agent(store, client(service.url), RepeatOrder())
agent.submit("o-100", "Return my unused item.", "repeat-check")
agent.run("repeat-check", rounds=3)
agent.run("repeat-check", rounds=3)
error = None
try:
agent.run("repeat-check", rounds=3)
except LabError as exc:
error = exc.code
task = store.inspect("repeat-check")
tools = [e for e in task["events"] if e["kind"] == "tool"]
failures = [e["payload"]["reason"] for e in task["events"] if e["kind"] == "failure"]
audit = client(service.url, "admin-token").request("GET", "/v1/audit")
count = sum(r["task_id"] == "repeat-check" for r in audit["returns"])
print(json.dumps({"status": task["status"], "checkpoint_tools": task["tool_count"],
"tool_events": len(tools), "error": error, "failure_events": failures,
"business_returns": count}, sort_keys=True), flush=True)
assert error == "tool_budget_exhausted", "cross-run tool budget was reset"
assert len(tools) == 6 and task["tool_count"] == 6
assert count == 0
finally:
store.close()
'''
(box / "check_loop.py").write_text(check)
run = subprocess.run([sys.executable, "check_loop.py"], cwd=box, capture_output=True, text=True)
print(run.stdout.strip())
print("fault_exit=" + str(run.returncode))
assert run.returncode == 1 and "cross-run tool budget was reset" in run.stderr, run.stderr
assert json.loads(run.stdout)["tool_events"] == 9
print("Repair only the copied agent.py in:", box)
print("Then run:", sys.executable, str(box / "check_loop.py"))
Read the failure before repairing
The faulty check prints status="queued", checkpoint_tools=3, tool_events=9, no error, no failure events and business_returns=0. Its child process exits nonzero on cross-run tool budget was reset; the outer reproducer prints fault_exit=1. Nine committed tool events refute the apparent checkpoint count of three. Trace backwards from that mismatch to the inserted BUG_RESET_BUDGET line, rather than increasing the configured quota or classifying the loop as completed.
Repair only the printed temporary agent.py: remove the one line containing BUG_RESET_BUDGET. Do not change MAX_TOOLS, the assertions or the repeated-read stub. Run the printed check_loop.py command again. Each check creates a fresh database, so this rerun cannot inherit nine receipts from the faulty check. It must exit zero with status="failed", checkpoint_tools=6, tool_events=6, error="tool_budget_exhausted", failure_events=["tool_budget_exhausted"] and zero business returns. The third invocation records a candidate model response but dispatches no seventh tool.
Write an incident note with the two outputs, the exact state-reset cause and the restored invariant. This is a source-copy repair exercise, not merely running the supplied project tests. It verifies this successful-read budget; failed HTTP attempts and external writes remain separate boundaries.
code example
Another boundary can mask the intended fault
Disabling only the batch preflight still leaves Agent.tool’s per-tool guard. Seeing tool_budget_exhausted after that edit does not prove the preflight ran. A fault experiment must identify which independent guard could stop the same input and inspect the event count before claiming coverage.
Acceptance task for this level
Run the temporary-copy reproducer, explain the 3-versus-9 counter/event mismatch, remove the injected reset line in that copy, and rerun its unchanged check. Submit both outputs and a short evidence→cause→repair note.
Reading this browser’s record…
Hide the answer and check your understanding
Why must the repeated-read stub use a fresh call ID for each same-argument action?
Expand reference derivation
Reusing the same call ID triggers duplicate_model_call_id or receipt reuse and prevents the nine-call failure from appearing. The experiment isolates lifetime budget persistence by allowing valid fresh candidates with repeated semantics. Production repeat detection can additionally compare normalized action/argument signatures, but that detector is not implemented by this demo.
Further explanations and practice
When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.
All linked explanations and exercises (1 )
Sources and verification scope
The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.