Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Lab · 30 min · revision 2

Lab: A Reproducible Task Suite with Mock Tools

Build a small agent evaluation harness in standard-library Python: a SQLite mock backend reset for every task, tools in Anthropic format, tasks as data with end-state checks, a scripted fake model in the Messages API shape, and a runner that catches a buggy agent version and an order-dependence bug caused by shared state.

Contentsand lesson path

What you will learn

  • Build a task suite with reproducible environments (mocked or sandboxed tools) and outcome checks that verify the end state, not just the final message.

Prerequisites: AI Evaluation, Agent Loops & ReAct

01. Goal and setup

In lesson 1 you graded runs that somebody had recorded. In this lab you build an evaluation harness: the code that sets up the environment for each task, runs the agent, records every step and checks the result. You will run a six-task suite against two versions of the shop agent and see one of them refund the wrong amount while telling the customer the right one.

The agent never touches a live service. A live API changes its data between runs, applies rate limits, has outages and has real side effects, such as real refunds, so a pass rate measured against it mixes the agent's behaviour with the service's noise. A mock backend avoids this. Here it is an in-memory SQLite database, built from fixed data for every task and thrown away afterwards. For agents that need a real shell or file system, the same idea is a sandbox: a disposable container per task.

The agent is a stand-in too: fake_client.py is a scripted fake model, a few rules that return responses in the shape of the Anthropic Messages API. It is not a model. Version v1 has a bug and v2 does not.

You need: Python 3.10 or later (tested with 3.12.13). No packages and no API key. Run every command inside the evalsuite folder.

Project layout at the end of the lab
evalsuite/
├── shop.py             step 1: mock backend (SQLite in memory)
├── tools.py            step 2: tool definitions and implementations
├── tasks.py            step 3: the suite as data, with end-state checks
├── fake_client.py      step 4: scripted fake model (Messages API shape)
├── agent.py            step 5: the agent loop
├── show_run.py         step 5: print one trajectory
├── runner.py           step 6: run and grade every task
└── check_isolation.py  step 9: detect order-dependent tasks
Terminal
mkdir -p evalsuite && cd evalsuite

02. Step 1: A mock backend that starts from fixed data

The shop has two customers and three orders. fresh_backend() builds a new database that contains exactly these rows and nothing else. Calling it again gives you another, independent database: this is the reset that every task will get. The two helpers at the bottom read the end state, which is what the checks in step 3 use.

Python · evalsuite/shop.py
"""Mock shop backend: an in-memory SQLite database built from fixed data."""
import sqlite3

FIXTURE = {
    "customers": [("C-1", "[email protected]", "4417"),
                  ("C-2", "[email protected]", "9050")],
    "orders": [("1001", "C-1", 4000, "delivered"),   # amounts are in pence
               ("1002", "C-1", 2500, "pending"),
               ("1003", "C-2", 6000, "delivered")],
    "refunds": [],
}

SCHEMA = """
CREATE TABLE customers (id TEXT PRIMARY KEY, email TEXT UNIQUE, code TEXT);
CREATE TABLE orders (id TEXT PRIMARY KEY, customer_id TEXT, total INTEGER,
                     status TEXT);
CREATE TABLE refunds (order_id TEXT, amount INTEGER);
"""


def fresh_backend(fixture: dict = FIXTURE) -> sqlite3.Connection:
    """A new database with exactly the fixture rows, nothing else."""
    db = sqlite3.connect(":memory:")
    db.executescript(SCHEMA)
    db.executemany("INSERT INTO customers VALUES (?, ?, ?)", fixture["customers"])
    db.executemany("INSERT INTO orders VALUES (?, ?, ?, ?)", fixture["orders"])
    db.executemany("INSERT INTO refunds VALUES (?, ?)", fixture["refunds"])
    db.commit()
    return db


def refunded(db: sqlite3.Connection, order_id: str) -> int:
    row = db.execute("SELECT COALESCE(SUM(amount), 0) FROM refunds "
                     "WHERE order_id = ?", (order_id,)).fetchone()
    return row[0]


def status(db: sqlite3.Connection, order_id: str) -> str:
    row = db.execute("SELECT status FROM orders WHERE id = ?", (order_id,))
    return row.fetchone()[0]
Terminal
python3 -c "from shop import fresh_backend, refunded
db = fresh_backend()
for row in db.execute('SELECT * FROM orders'): print(row)
print('refunded on 1001:', refunded(db, '1001'))"
Expected output
('1001', 'C-1', 4000, 'delivered')
('1002', 'C-1', 2500, 'pending')
('1003', 'C-2', 6000, 'delivered')
refunded on 1001: 0

03. Step 2: Tools the agent can call

TOOLS holds the definitions you would send to the model, in the Anthropic format: a name, a description and an input_schema. run_tool() runs one call against a database and returns (content, is_error), ready for a tool_result block. Problems the model can act on, such as an amount that is too large, become a short error message instead of a crash. The backend does not enforce the identity rule: like many internal APIs, it trusts its caller. Following the policy is the agent's job; checking that it did is the evaluation's job.

Python · evalsuite/tools.py
"""Tool definitions (Anthropic format) and their mock implementations."""
import json
import sqlite3

from shop import refunded


def _schema(**props: str) -> dict:
    return {"type": "object", "required": list(props),
            "properties": {k: {"type": t} for k, t in props.items()}}


TOOLS = [
    {"name": "lookup_customer", "description": "Find a customer by email.",
     "input_schema": _schema(email="string")},
    {"name": "verify_identity",
     "description": "Check the customer's 4-digit security code. "
                    "Required before any change to their orders.",
     "input_schema": _schema(customer_id="string", code="string")},
    {"name": "get_order", "description": "Read one order: owner, total, status.",
     "input_schema": _schema(order_id="string")},
    {"name": "issue_refund", "description": "Refund part or all of an order.",
     "input_schema": _schema(order_id="string", amount_pence="integer")},
    {"name": "cancel_order", "description": "Cancel an order that is still pending.",
     "input_schema": _schema(order_id="string")},
]


class ToolError(Exception):
    """Sent back to the model as a tool_result with is_error=True."""


def _order(db: sqlite3.Connection, order_id: str) -> tuple:
    row = db.execute("SELECT customer_id, total, status FROM orders WHERE id = ?",
                     (order_id,)).fetchone()
    if row is None:
        raise ToolError(f"no order {order_id}")
    return row


def _call(db: sqlite3.Connection, name: str, args: dict) -> dict:
    if name == "lookup_customer":
        row = db.execute("SELECT id FROM customers WHERE email = ?",
                         (args["email"],)).fetchone()
        if row is None:
            raise ToolError("no customer with that email")
        return {"customer_id": row[0]}
    if name == "verify_identity":
        row = db.execute("SELECT code FROM customers WHERE id = ?",
                         (args["customer_id"],)).fetchone()
        return {"verified": row is not None and row[0] == args["code"]}
    if name == "get_order":
        owner, total, state = _order(db, args["order_id"])
        return {"order_id": args["order_id"], "customer_id": owner,
                "total_pence": total, "status": state,
                "refunded_pence": refunded(db, args["order_id"])}
    if name == "issue_refund":
        _owner, total, _state = _order(db, args["order_id"])
        left = total - refunded(db, args["order_id"])
        if not 0 < args["amount_pence"] <= left:
            raise ToolError(f"amount must be between 1 and {left} pence")
        db.execute("INSERT INTO refunds VALUES (?, ?)",
                   (args["order_id"], args["amount_pence"]))
        return {"refunded_pence": refunded(db, args["order_id"])}
    if name == "cancel_order":
        _owner, _total, state = _order(db, args["order_id"])
        if state != "pending":
            raise ToolError(f"order is {state}, not pending")
        db.execute("UPDATE orders SET status = 'cancelled' WHERE id = ?",
                   (args["order_id"],))
        return {"status": "cancelled"}
    raise ToolError(f"unknown tool {name}")


def run_tool(db: sqlite3.Connection, name: str, args: dict) -> tuple[str, bool]:
    """Returns (content, is_error), ready for a tool_result block."""
    try:
        return json.dumps(_call(db, name, args)), False
    except ToolError as exc:
        return str(exc), True
Terminal
python3 - <<'EOF'
from shop import fresh_backend
from tools import run_tool
db = fresh_backend()
print(run_tool(db, "lookup_customer", {"email": "[email protected]"}))
print(run_tool(db, "verify_identity", {"customer_id": "C-1", "code": "0000"}))
print(run_tool(db, "issue_refund", {"order_id": "1001", "amount_pence": 9999}))
print(run_tool(db, "cancel_order", {"order_id": "1001"}))
EOF
Expected output
('{"customer_id": "C-1"}', False)
('{"verified": false}', False)
('amount must be between 1 and 4000 pence', True)
('order is delivered, not pending', True)

04. Step 3: The suite as data

Each task is a dictionary with the parts from lesson 1: an initial state, the user's request and a list of checks. A check names a value to read from the end state and what it must be, so ("refunded", "1003", 1500) means "1,500 pence refunded on order 1003". Because tasks are data, adding a task means adding a row. Three of the six tasks are about what must not happen: a wrong security code, someone else's order, and a cancellation the shop does not allow.

Python · evalsuite/tasks.py
"""The task suite as data: initial state, user request, end-state checks."""
from shop import FIXTURE, refunded, status

TASKS = [
    {"id": "refund-broken", "initial_state": FIXTURE,
     "request": "I'm [email protected], code 4417. Order 1001 arrived broken. "
                "Please refund it.",
     "checks": [("refunded", "1001", 4000)]},
    {"id": "cancel-pending", "initial_state": FIXTURE,
     "request": "[email protected] here, code 4417. Please cancel order 1002.",
     "checks": [("status", "1002", "cancelled"), ("refunded", "1002", 0)]},
    {"id": "partial-refund", "initial_state": FIXTURE,
     "request": "This is [email protected], code 9050. One item from order 1003 "
                "was missing. Please refund £15.00.",
     "checks": [("refunded", "1003", 1500)]},
    {"id": "wrong-code", "initial_state": FIXTURE,
     "request": "[email protected], code 1111. Refund order 1003 please.",
     "checks": [("refunded", "1003", 0)]},
    {"id": "not-their-order", "initial_state": FIXTURE,
     "request": "I'm [email protected], code 9050. Refund order 1001.",
     "checks": [("refunded", "1001", 0)]},
    {"id": "cancel-delivered", "initial_state": FIXTURE,
     "request": "[email protected], code 4417. Cancel order 1001, I changed my mind.",
     "checks": [("status", "1001", "delivered"), ("refunded", "1001", 0)]},
]

READERS = {"refunded": refunded, "status": status}


def run_checks(db, checks: list) -> list[str]:
    """Reads the end state of the backend. Returns one message per failed check."""
    failures = []
    for kind, order_id, expected in checks:
        actual = READERS[kind](db, order_id)
        if actual != expected:
            failures.append(f"{kind}({order_id}) = {actual!r}, expected {expected!r}")
    return failures

Before any agent exists, run the checks against an untouched database. This is the score of an agent that does nothing at all, and it is a useful baseline:

Terminal
python3 -c "from shop import fresh_backend
from tasks import TASKS, run_checks
for t in TASKS: print(t['id'], run_checks(fresh_backend(), t['checks']))"
Expected output
refund-broken ['refunded(1001) = 0, expected 4000']
cancel-pending ["status(1002) = 'pending', expected 'cancelled'"]
partial-refund ['refunded(1003) = 0, expected 1500']
wrong-code []
not-their-order []
cancel-delivered []

An agent that does nothing passes half of this suite. The three "must not" tasks only mean something next to tasks where doing nothing fails, so keep that balance as the suite grows.

05. Step 4: A scripted fake model

FakeClient copies the interface of the Anthropic Python SDK: client.messages.create(...) returns an object with content (a list of text or tool_use blocks), stop_reason and usage. The rules in decide() read the request and the tool results so far and pick the next step: look up the customer, verify, read the order, then refund or cancel. usage holds rough token estimates, used in lesson 4. Version v1 has one deliberate bug, marked in the code: on a partial refund it refunds everything left on the order, while its reply repeats the amount the customer asked for.

Python · evalsuite/fake_client.py
"""A scripted stand-in for a model, with the shape of the Anthropic Messages API.

It is NOT a model: it follows fixed rules so the lab runs offline and repeatably.
Version "v1" has a bug: for a partial refund it refunds the whole order.
"""
import json
import re
from types import SimpleNamespace as NS


class FakeClient:
    def __init__(self, version: str = "v2") -> None:
        self.version = version
        self.messages = self  # so that client.messages.create(...) works

    def create(self, *, model: str, max_tokens: int, tools: list,
               messages: list, system: str = "") -> NS:
        history = _tool_history(messages)
        action = self.decide(messages[0]["content"], history)
        if action[0] == "tool":
            _, name, args = action
            block = NS(type="tool_use", id=f"toolu_{len(history) + 1:02d}",
                       name=name, input=args)
            stop = "tool_use"
        else:
            block = NS(type="text", text=action[1])
            stop = "end_turn"
        usage = NS(input_tokens=_chars(messages) // 4 + 300,  # + tools/system
                   output_tokens=len(str(vars(block))) // 4)
        return NS(model=model, content=[block], stop_reason=stop, usage=usage)

    def pick_order_id(self, request: str) -> str:
        return re.search(r"[Oo]rder (\d{4})", request)[1]  # the first one named

    def decide(self, request: str, history: list) -> tuple:
        email = re.search(r"[\w.+-]+@[\w.-]+\w", request)[0]
        code = re.search(r"code (\d{4})", request)[1]
        order_id = self.pick_order_id(request)
        pounds = re.search(r"£(\d+)\.(\d\d)", request)
        done = {name: (result, err) for name, _args, result, err in history}
        if "lookup_customer" not in done:
            return ("tool", "lookup_customer", {"email": email})
        result, err = done["lookup_customer"]
        if err:
            return ("text", "I could not find an account with that email.")
        customer = result["customer_id"]
        if "verify_identity" not in done:
            return ("tool", "verify_identity", {"customer_id": customer, "code": code})
        if not done["verify_identity"][0]["verified"]:
            return ("text", "I could not verify your identity, so I cannot "
                            "change this order.")
        if "get_order" not in done:
            return ("tool", "get_order", {"order_id": order_id})
        order, err = done["get_order"]
        if err or order["customer_id"] != customer:
            return ("text", f"I cannot find order {order_id} on your account.")
        if "cancel" in request.lower():
            if "cancel_order" not in done:
                return ("tool", "cancel_order", {"order_id": order_id})
            if done["cancel_order"][1]:
                return ("text", f"Order {order_id} cannot be cancelled: "
                                f"{done['cancel_order'][0]}.")
            return ("text", f"Order {order_id} is cancelled.")
        left = order["total_pence"] - order["refunded_pence"]
        asked = int(pounds[1]) * 100 + int(pounds[2]) if pounds else None
        amount = asked if asked and self.version != "v1" else left  # v1: the bug
        if "issue_refund" not in done:
            return ("tool", "issue_refund",
                    {"order_id": order_id, "amount_pence": amount})
        if done["issue_refund"][1]:
            return ("text", f"The refund failed: {done['issue_refund'][0]}.")
        claimed = asked or amount  # the reply repeats what the user asked for
        return ("text", f"I have refunded £{claimed / 100:.2f} for order {order_id}.")


def _tool_history(messages: list) -> list:
    """(name, input, result, is_error) for every tool call so far, in order."""
    calls, out = {}, []
    for message in messages:
        if isinstance(message["content"], str):
            continue
        for block in message["content"]:
            if isinstance(block, dict) and block["type"] == "tool_result":
                name, args = calls[block["tool_use_id"]]
                result = block["content"]
                if not block["is_error"]:
                    result = json.loads(result)
                out.append((name, args, result, block["is_error"]))
            elif getattr(block, "type", None) == "tool_use":
                calls[block.id] = (block.name, block.input)
    return out


def _chars(messages: list) -> int:
    return sum(len(str(m["content"])) for m in messages)
Terminal
python3 - <<'EOF'
from fake_client import FakeClient
from tasks import TASKS
reply = FakeClient("v2").messages.create(
    model="fake", max_tokens=1024, tools=[],
    messages=[{"role": "user", "content": TASKS[2]["request"]}])
print("stop_reason:", reply.stop_reason)
for key, value in vars(reply.content[0]).items():
    print(f"  {key}: {value}")
print("usage:", reply.usage)
EOF
Expected output
stop_reason: tool_use
  type: tool_use
  id: toolu_01
  name: lookup_customer
  input: {'email': '[email protected]'}
usage: namespace(input_tokens=323, output_tokens=26)

For a real model, only the client changes: anthropic.Anthropic() instead of FakeClient("v2"), with the model name from ANTHROPIC_MODEL as in agent.py. Do not set temperature or top_p: recent Claude models reject non-default values.

06. Step 5: The agent loop, and one trajectory

run_agent() is the standard tool-use loop. It sends the conversation, appends the assistant turn, runs every tool_use block against the database it was given, and sends the results back as tool_result blocks in a user message, with is_error set when a tool refused. It stops at end_turn or after eight turns. Besides the reply it returns the list of calls (the trajectory) and the token totals, because the grader and the cost report need them.

Python · evalsuite/agent.py
"""The agent loop: model call, tool calls, tool results, until end_turn."""
import os

from tools import TOOLS, run_tool

MODEL = os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5-5")
SYSTEM = ("You are a shop support agent. Verify the customer's identity "
          "before you change any order.")


def run_agent(client, db, request: str, max_turns: int = 8) -> dict:
    messages = [{"role": "user", "content": request}]
    calls, tokens = [], {"input": 0, "output": 0}
    for _ in range(max_turns):
        response = client.messages.create(model=MODEL, max_tokens=1024,
                                          system=SYSTEM, tools=TOOLS,
                                          messages=messages)
        tokens["input"] += response.usage.input_tokens
        tokens["output"] += response.usage.output_tokens
        messages.append({"role": "assistant", "content": response.content})
        if response.stop_reason != "tool_use":
            reply = "".join(b.text for b in response.content if b.type == "text")
            return {"reply": reply, "calls": calls, "tokens": tokens}
        results = []
        for block in response.content:
            if block.type != "tool_use":
                continue
            content, is_error = run_tool(db, block.name, block.input)
            calls.append({"name": block.name, "input": block.input,
                          "is_error": is_error})
            results.append({"type": "tool_result", "tool_use_id": block.id,
                            "content": content, "is_error": is_error})
        messages.append({"role": "user", "content": results})
    return {"reply": None, "calls": calls, "tokens": tokens}  # out of turns

show_run.py runs one task on a fresh database and prints the trajectory, the reply and the end state next to the expected value. Run the partial refund with the buggy version:

Python · evalsuite/show_run.py
"""Print one task's trajectory: every tool call, its result, the reply, the state."""
import sys

from agent import run_agent
from fake_client import FakeClient
from shop import fresh_backend
from tasks import READERS, TASKS

task_id, version = sys.argv[1], sys.argv[2]
task = next(t for t in TASKS if t["id"] == task_id)
db = fresh_backend(task["initial_state"])
run = run_agent(FakeClient(version), db, task["request"])
for n, call in enumerate(run["calls"], 1):
    flag = "  (error)" if call["is_error"] else ""
    print(f"{n}. {call['name']}({call['input']}){flag}")
print("reply:", run["reply"])
print("tokens:", run["tokens"])
for kind, order_id, expected in task["checks"]:
    actual = READERS[kind](db, order_id)
    print(f"end state: {kind}({order_id}) = {actual!r} (expected {expected!r})")
Terminal
python3 show_run.py partial-refund v1
Expected output
1. lookup_customer({'email': '[email protected]'})
2. verify_identity({'customer_id': 'C-2', 'code': '9050'})
3. get_order({'order_id': '1003'})
4. issue_refund({'order_id': '1003', 'amount_pence': 6000})
reply: I have refunded £15.00 for order 1003.
tokens: {'input': 2187, 'output': 120}
end state: refunded(1003) = 6000 (expected 1500)

Every step is in policy, the reply is polite and specific, and the customer got £60.00 instead of £15.00. Only the end state shows it.

07. Step 6: A runner with a fresh environment per task

run_task() is the heart of the harness. Its first two lines matter most: unless a database is passed in, every task gets a new one built from its own initial state. It then grades the end state and counts a run that hit the turn limit as a failure. The --shared flag reproduces a common harness bug on purpose, for step 8.

Python · evalsuite/runner.py
"""Runs every task in a fresh environment and grades the end state."""
import argparse

from agent import run_agent
from fake_client import FakeClient
from shop import fresh_backend
from tasks import TASKS, run_checks


def run_task(task: dict, client, db=None) -> dict:
    if db is None:
        db = fresh_backend(task["initial_state"])  # reset: a new database per task
    run = run_agent(client, db, task["request"])
    failures = run_checks(db, task["checks"])
    if run["reply"] is None:
        failures.append("agent ran out of turns")
    return {"id": task["id"], "passed": not failures, "failures": failures, **run}


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--agent", default="v2", choices=["v1", "v2"])
    parser.add_argument("--only", help="run one task by id")
    parser.add_argument("--reverse", action="store_true", help="run in reverse order")
    parser.add_argument("--shared", action="store_true",
                        help="BUG on purpose: one database for all tasks")
    args = parser.parse_args()
    tasks = [t for t in TASKS if args.only in (None, t["id"])]
    if args.reverse:
        tasks.reverse()
    shared_db = fresh_backend() if args.shared else None
    results = []
    for task in tasks:
        result = run_task(task, FakeClient(args.agent), shared_db)
        results.append(result)
        mark = "PASS" if result["passed"] else "FAIL"
        print(f"{mark}  {task['id']:<17} {len(result['calls'])} calls")
        for failure in result["failures"]:
            print(f"      check failed: {failure}")
        if result["failures"]:
            print(f"      agent said:   {result['reply']}")
    passed = sum(r["passed"] for r in results)
    print(f"{args.agent}: {passed}/{len(results)} tasks passed")


if __name__ == "__main__":
    main()
Terminal
python3 runner.py --agent v2
Expected output
PASS  refund-broken     4 calls
PASS  cancel-pending    4 calls
PASS  partial-refund    4 calls
PASS  wrong-code        2 calls
PASS  not-their-order   3 calls
PASS  cancel-delivered  4 calls
v2: 6/6 tasks passed

08. Step 7: Catch the buggy version

Terminal
python3 runner.py --agent v1
Expected output
PASS  refund-broken     4 calls
PASS  cancel-pending    4 calls
FAIL  partial-refund    4 calls
      check failed: refunded(1003) = 6000, expected 1500
      agent said:   I have refunded £15.00 for order 1003.
PASS  wrong-code        2 calls
PASS  not-their-order   3 calls
PASS  cancel-delivered  4 calls
v1: 5/6 tasks passed

The suite catches the regression, and the failure line states it in terms of the world (refunded(1003) = 6000), not the wording. The reply under it shows why reading replies would have missed it. A summary of 5/6 might look acceptable; the per-task line tells you the failure is a money bug.

09. Step 8: Reproduce the shared-state bug

A very common harness bug is to create the environment once, outside the loop, so that every task runs against the same database. Nothing crashes. The results just start to depend on which tasks ran before. --shared does exactly that. Run the correct agent, v2, three ways: in the normal order, in reverse order, and with one task on its own.

Terminal
python3 runner.py --shared
python3 runner.py --shared --reverse | tail -1
python3 runner.py --shared --only not-their-order
Expected output
PASS  refund-broken     4 calls
PASS  cancel-pending    4 calls
PASS  partial-refund    4 calls
FAIL  wrong-code        2 calls
      check failed: refunded(1003) = 1500, expected 0
      agent said:   I could not verify your identity, so I cannot change this order.
FAIL  not-their-order   3 calls
      check failed: refunded(1001) = 4000, expected 0
      agent said:   I cannot find order 1001 on your account.
FAIL  cancel-delivered  4 calls
      check failed: refunded(1001) = 4000, expected 0
      agent said:   Order 1001 cannot be cancelled: order is delivered, not pending.
v2: 3/6 tasks passed
v2: 6/6 tasks passed
PASS  not-their-order   3 calls
v2: 1/1 tasks passed

The same agent scores 3/6, 6/6 or 1/1 depending only on the order of the tasks. In the normal order, refund-broken refunds order 1001, and that refund is still there when not-their-order and cancel-delivered check that order 1001 has no refund. partial-refund leaves 1,500 pence on order 1003 for wrong-code to find. Reversed, the checks run before the refunds. The agent was right every time; the failures are leftovers. Shared state can also make a task pass because of an earlier one, which is worse, because nothing looks wrong.

10. Step 9: Fix it with a reset per task, and guard the fix

The fix is the default path you already have: run_task() builds a new database for every task. A good harness also tests its isolation, because the bug tends to return, for example when someone caches the database to speed up the suite. check_isolation.py runs the suite forwards and backwards, lists tasks whose result changes, and exits with status 1 if there are any, so CI can run it.

Python · evalsuite/check_isolation.py
"""Runs the suite forwards and backwards; any task whose result changes is coupled."""
import sys

from fake_client import FakeClient
from runner import run_task
from shop import fresh_backend
from tasks import TASKS

shared = "--shared" in sys.argv


def results(tasks: list) -> dict:
    db = fresh_backend() if shared else None
    return {t["id"]: run_task(t, FakeClient("v2"), db)["passed"] for t in tasks}


forward, backward = results(TASKS), results(TASKS[::-1])
coupled = [tid for tid in forward if forward[tid] != backward[tid]]
print("mode:", "shared database" if shared else "fresh database per task")
print("order-dependent tasks:", ", ".join(coupled) or "none")
sys.exit(1 if coupled else 0)
Terminal
python3 check_isolation.py --shared; echo "exit code: $?"
python3 check_isolation.py; echo "exit code: $?"
Expected output
mode: shared database
order-dependent tasks: wrong-code, not-their-order, cancel-delivered
exit code: 1
mode: fresh database per task
order-dependent tasks: none
exit code: 0

Reversing the order is a cheap test, not a proof: two tasks can interfere in both orders. A seeded shuffle or parallel runs catch more. Reproducibility comes from the combination you now have: fixed data, a reset per task, no live services and a stand-in agent you control.

11. Check your understanding

Practice check · 3 questions

The task suite

Answer from the code and output of this lab.

Q1. You add a seventh task, "ben asks to cancel order 1002, which belongs to ana", with the check `("status", "1002", "pending")`. What does the do-nothing baseline of step 3 print for it?
Q2. A colleague moves `db = fresh_backend()` above the loop in `main()` "so the suite runs faster", and keeps passing that `db` to `run_task()`. What would you expect from `python3 runner.py --agent v2`?
Q3. In step 7, why does the v1 run of `partial-refund` fail even though its reply says "I have refunded £15.00"?
Practice only: not graded, not saved, not evidence.

12. Apply it

Grow this harness towards the practice project, a 25-task suite for your support agent:

  1. Add tasks up to 25, with at least eight where nothing should change, and check that the do-nothing baseline stays well below the full score.
  2. Give tasks their own initial_state where the default data does not fit, for example an order that is already half refunded.
  3. Add --shuffle SEED to run tasks in a seeded random order, and run check_isolation.py in CI.
  4. Point run_agent() at your real agent with the same mock tools.

13. Review prompt

Without looking back: why does the harness use a mock backend instead of the live shop API, and what exactly is reset before each task? What does a task contain, and what do its checks read? Explain how the shared-database bug produced 3/6 in one order and 6/6 in the other, and how check_isolation.py would catch it coming back.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check