Lesson 52.3 · 3 of 6 · 8 min read · Reviewed 24 Nov 2026
Lab: loop until the tests pass
By the end, you can
- Build a write, test, fix state graph in plain Python.
- Guard the cycle with a max-iterations limit and report the outcome honestly.
This lesson is a lab. You will build the coding graph from 102.2 in plain Python, with no framework, so every moving part is visible. The Playground version is in the lab panel below; this page explains the design.
The pieces
State. One dict with the task, the current code, the test results and an attempt counter.
Nodes. Three functions:
writedrafts the first version of the code.testruns the test cases against the code and recordspassedand the list offailures.fixreads the failures and produces a new version, adding one toattempts.
In the lab the “model” is simulated: fix returns the next, slightly better version of an apply_discount function, as a model would after reading the failures. The tests really run against each version. That keeps the run deterministic, so you can see the loop structure clearly. In a real agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done., write and fix would be model calls and test would run your real test suite.
Router. After test, one function decides where to go:
def after_test(state):
if state["passed"]:
return "done"
if state["attempts"] >= MAX_ATTEMPTS:
return "give_up"
return "fix"
The runner
A graph runtime is smaller than it sounds:
EDGES = {"write": "test", "fix": "test", "test": after_test}
def run(state, start="write"):
node = start
while node not in ("done", "give_up"):
update = NODES[node](state)
state = {**state, **update} # merge the update
trace.append((node, update))
nxt = EDGES[node]
node = nxt(state) if callable(nxt) else nxt
state["status"] = "passed" if node == "done" else "gave_up"
return state
Fixed edges are strings. Conditional edges are functions. The runner treats them the same way: ask the edge for the next node name.
What to look for when it runs
| Round | Node | Failures | attempts |
|---|---|---|---|
| 1 | write, test | 5 | 0 |
| 2 | fix, test | 2 | 1 |
| 3 | fix, test | 1 | 2 |
| 4 | fix, test | 0 | 3 |
The run ends with status: passed after 3 fixes. Now set MAX_ATTEMPTS = 2 and run it again: the router sends the run to give_up, and the status says so, with the last failure in the state for a person to read.
Extensions to try
- Break the fixer so it never changes the code. The guard should end the run at the cap.
- Add a review node after
donethat rejects code containing aprintcall and routes back tofix. Now the cycle has two ways back in, and the same counter must guard both. - Print a traceTrace: A record of everything that happened during one request or agent run, as a tree of timed steps. line per step with the node name and the fields it changed. That is exactly the event streamStreaming: Receiving a response as a series of server-sent events while it is generated, instead of waiting for the whole reply. you will send to a UI in 102.5.
Common mistakes
- Merging by replacing the whole state. A node that returns
{"code": ...}would wipe every other field. Merge updates; don’t replace. - Incrementing the counter in the router. Routers should only read. Increment in the node that starts each round.
- Trusting the fixer’s claim. The only thing that sets
passedis the test node.
Key points
- A graph runner is a short loop: run the current node, merge its update into the state, ask the edge which node is next.
- The test node is ground truth: it runs real checks and writes passed and failures into the state.
- The router after test picks done, fix or give up, and the attempt counter keeps the cycle bounded.
- A run ends with a clear status, either passed or gave_up, never a silent success.
Loop write, test, fix until green
Build a plain-Python state graph whose write, test, fix cycle runs until real tests pass, bounded by a max-iterations guard.
You will have: A graph runner with three nodes, a router and a guard, plus traces of a passing run and a stuck run.
Steps
- Run the starter: the router says done after the first test, even with 5 failures.
- Write fix() so it returns the next code version and adds one to attempts.
- Write after_test() to route to done, give_up or fix from the state.
- Run it and watch the failures fall 5, 2, 1, 0.
- Set BROKEN_FIXER = True and confirm the guard ends the run with gave_up after MAX_ATTEMPTS.
Done when
- The main run ends with status passed after 3 attempts.
- The broken-fixer run ends with status gave_up after 4 attempts and prints the last failure.
- Only the test node ever sets passed.
Open in the Playground No API key needed.
Starter code (Python)
# Lab: a plain-Python state graph that loops write -> test -> fix until the tests pass.
# The "model" is simulated: it returns the next version of the code. The tests really run.
VERSIONS = [
"def apply_discount(price, pct):\n return price * pct / 100",
"def apply_discount(price, pct):\n return price * (1 - pct / 100)",
"def apply_discount(price, pct):\n return max(0.0, price * (1 - pct / 100))",
"def apply_discount(price, pct):\n return round(max(0.0, price * (1 - pct / 100)), 2)",
]
CASES = [((100, 10), 90.0), ((80, 25), 60.0), ((50, 0), 50.0), ((20, 150), 0.0), ((19.99, 10), 17.99)]
MAX_ATTEMPTS = 4
BROKEN_FIXER = False # set True to see the guard end a run that can never pass
def write(s):
return {"code": VERSIONS[0], "version": 0}
def test(s):
env = {}
exec(s["code"], env)
fn = env["apply_discount"]
failures = [f"apply_discount{args} gave {fn(*args)!r}, want {want}" for args, want in CASES if fn(*args) != want]
return {"failures": failures, "passed": not failures}
def fix(s):
# TODO: simulated model call. Use the next version (unless BROKEN_FIXER) and add one to attempts
return {}
def after_test(s):
# TODO: "done" if passed, "give_up" if attempts reached MAX_ATTEMPTS, else "fix"
return "done"
NODES = {"write": write, "test": test, "fix": fix}
EDGES = {"write": "test", "fix": "test", "test": after_test} # strings are fixed edges, functions are routers
def run():
state = {"task": "apply_discount passes every case", "attempts": 0}
node = "write"
while node not in ("done", "give_up"):
update = NODES[node](state)
state = {**state, **update} # merge, never replace
if node == "test":
print(f"test: {len(state['failures'])} failing, attempts {state['attempts']}")
nxt = EDGES[node]
node = nxt(state) if callable(nxt) else nxt
state["status"] = "passed" if node == "done" else "gave_up"
return state
final = run()
print(f"status: {final['status']}, attempts: {final['attempts']}")
if final["failures"]:
print("last failure:", final["failures"][0])
Show a solution
# Lab: a plain-Python state graph that loops write -> test -> fix until the tests pass.
# The "model" is simulated: it returns the next version of the code. The tests really run.
VERSIONS = [
"def apply_discount(price, pct):\n return price * pct / 100",
"def apply_discount(price, pct):\n return price * (1 - pct / 100)",
"def apply_discount(price, pct):\n return max(0.0, price * (1 - pct / 100))",
"def apply_discount(price, pct):\n return round(max(0.0, price * (1 - pct / 100)), 2)",
]
CASES = [((100, 10), 90.0), ((80, 25), 60.0), ((50, 0), 50.0), ((20, 150), 0.0), ((19.99, 10), 17.99)]
MAX_ATTEMPTS = 4
BROKEN_FIXER = False # set True to see the guard end a run that can never pass
def write(s):
return {"code": VERSIONS[0], "version": 0}
def test(s):
env = {}
exec(s["code"], env)
fn = env["apply_discount"]
failures = [f"apply_discount{args} gave {fn(*args)!r}, want {want}" for args, want in CASES if fn(*args) != want]
return {"failures": failures, "passed": not failures}
def fix(s):
v = s["version"] if BROKEN_FIXER else min(s["version"] + 1, len(VERSIONS) - 1)
return {"code": VERSIONS[v], "version": v, "attempts": s["attempts"] + 1}
def after_test(s):
if s["passed"]:
return "done"
if s["attempts"] >= MAX_ATTEMPTS:
return "give_up"
return "fix"
NODES = {"write": write, "test": test, "fix": fix}
EDGES = {"write": "test", "fix": "test", "test": after_test} # strings are fixed edges, functions are routers
def run():
state = {"task": "apply_discount passes every case", "attempts": 0}
node = "write"
while node not in ("done", "give_up"):
update = NODES[node](state)
state = {**state, **update} # merge, never replace
if node == "test":
print(f"test: {len(state['failures'])} failing, attempts {state['attempts']}")
nxt = EDGES[node]
node = nxt(state) if callable(nxt) else nxt
state["status"] = "passed" if node == "done" else "gave_up"
return state
final = run()
print(f"status: {final['status']}, attempts: {final['attempts']}")
if final["failures"]:
print("last failure:", final["failures"][0])
# The same graph with a fixer that never changes the code: the guard ends it.
BROKEN_FIXER = True
stuck = run()
print(f"broken fixer -> status: {stuck['status']}, attempts: {stuck['attempts']}")