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 5 of 6 · Worked example · 15 min · revision 2

From Production Trace to Regression Task

Turn a failed production trace into a regression task: redact personal data, rebuild the mocked state from recorded tool results, write the expected outcome, and prove that the task fails on the buggy agent and passes on the fix. Then run the suite in CI tiers with a gate that exits non-zero, and use online evaluation on sampled traffic as a signal to investigate.

Contentsand lesson path

What you will learn

  • Run agent evaluations in CI and on sampled production traffic, and turn traced production failures into new regression tasks.

Prerequisites: AI Evaluation, Agent Loops & ReAct

01. The problem

A customer writes in. She asked for a refund on order 1006, which arrived broken, and got money back for order 1005, which arrived fine. The suite from lab 2 is green for the version in production, v2: production has found a case no task covers, a request that names two orders.

You will turn the trace of that conversation into a regression task, a task whose job is to fail if this bug comes back. Anthropic's guide to agent evaluations contrasts these with capability tasks, which are meant to be hard and start with low pass rates; regression tasks should pass nearly all the time, so any failure is news. You will prove that the task fails on the buggy version and passes on the fix, run the suite in CI tiers, and close the loop with online evaluation. You need the evalsuite folder from lab 2 and Python 3.10 or later (tested with 3.12). Run every command inside evalsuite.

Terminal
cd evalsuite && ls agent.py fake_client.py runner.py shop.py tasks.py

02. Step 1: Read the trace

export_trace.py stands in for downloading the trace from your tracing backend. The spans are simplified but named after the OpenTelemetry GenAI conventions that the spans lab uses, and content capture was on, so arguments and results are recorded. All values are fictional. read_trace.py prints the run turn by turn.

Python · evalsuite/export_trace.py
"""Writes prod_trace.json: stands in for exporting one trace from your backend.

Simplified spans named after the OpenTelemetry GenAI conventions, exported with
content capture on. Every value here is fictional test data.
"""
import json

REQUEST = ("Hi, it's Carla Diaz ([email protected]), code 2291. Order 1005 "
           "arrived fine, but order 1006 is broken. Please refund order 1006.")


def tool(name: str, arguments: dict, result: dict) -> dict:
    return {"name": f"execute_tool {name}",
            "attributes": {"gen_ai.tool.name": name,
                           "gen_ai.tool.call.arguments": arguments,
                           "gen_ai.tool.call.result": result}}


def chat(key: str, role: str, text: str) -> dict:
    return {"name": "chat claude-sonnet-5-5", "attributes": {
        key: [{"role": role, "parts": [{"type": "text", "content": text}]}]}}


TRACE = {"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "agent_version": "v2",
         "spans": [
             chat("gen_ai.input.messages", "user", REQUEST),
             tool("lookup_customer", {"email": "[email protected]"},
                  {"customer_id": "C-7"}),
             tool("verify_identity", {"customer_id": "C-7", "code": "2291"},
                  {"verified": True}),
             tool("get_order", {"order_id": "1005"},
                  {"order_id": "1005", "customer_id": "C-7", "total_pence": 3200,
                   "status": "delivered", "refunded_pence": 0}),
             tool("issue_refund", {"order_id": "1005", "amount_pence": 3200},
                  {"refunded_pence": 3200}),
             chat("gen_ai.output.messages", "assistant",
                  "I have refunded £32.00 for order 1005."),
         ]}

with open("prod_trace.json", "w") as f:
    json.dump(TRACE, f, indent=1, ensure_ascii=False)
print("wrote prod_trace.json with", len(TRACE["spans"]), "spans")
Python · evalsuite/read_trace.py
"""Print a trace turn by turn: the request, each tool call, the reply."""
import json
import sys
import textwrap


def show(label: str, text: object) -> None:
    print(textwrap.fill(f"{label:<9} {text}", 80, subsequent_indent=" " * 10))


trace = json.load(open(sys.argv[1]))
print("trace", trace["trace_id"][:8], "agent", trace["agent_version"])
for span in trace["spans"]:
    a = span["attributes"]
    if "gen_ai.tool.name" in a:
        show(a["gen_ai.tool.name"], a["gen_ai.tool.call.arguments"])
        show("", f"-> {a['gen_ai.tool.call.result']}")
    for key in ("gen_ai.input.messages", "gen_ai.output.messages"):
        for message in a.get(key, []):
            show(message["role"], message["parts"][0]["content"])
Terminal
python3 export_trace.py && python3 read_trace.py prod_trace.json
Expected output
wrote prod_trace.json with 6 spans
trace 4bf92f35 agent v2
user      Hi, it's Carla Diaz ([email protected]), code 2291. Order 1005
          arrived fine, but order 1006 is broken. Please refund order 1006.
lookup_customer {'email': '[email protected]'}
          -> {'customer_id': 'C-7'}
verify_identity {'customer_id': 'C-7', 'code': '2291'}
          -> {'verified': True}
get_order {'order_id': '1005'}
          -> {'order_id': '1005', 'customer_id': 'C-7', 'total_pence': 3200,
          'status': 'delivered', 'refunded_pence': 0}
issue_refund {'order_id': '1005', 'amount_pence': 3200}
          -> {'refunded_pence': 3200}
assistant I have refunded £32.00 for order 1005.

Every span succeeded, so there is no error to start from. As in Reading a Failed Trace, find the first wrong step: get_order with 1005. The tool was right and the argument was wrong. The agent took the first order number in the message, which is exactly what pick_order_id() in fake_client.py does.

03. Step 2: Redact before you store anything

The trace holds a name, an email address and a security code. A regression task lives in the repository, appears in CI logs and is read by everyone who works on the agent, so it must not contain personal data. Redact consistently: the same email becomes the same placeholder in the request and in the tool arguments, so the task still fits together. Patterns find structured values such as email addresses, but not a name typed as free text, so the person triaging adds those by hand. The raw trace stays in the trace store, under its access rules and retention period.

Python · evalsuite/redact.py
"""Replace personal data with stable placeholders before a trace becomes a fixture."""
import json
import re

EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")
# Names in free text are not found by patterns: the person triaging adds them here.
KNOWN_VALUES = {"Carla Diaz": "Customer One"}


def redact_trace(trace: dict) -> dict:
    text = json.dumps(trace, ensure_ascii=False)
    emails = sorted(set(EMAIL.findall(text)))
    mapping = {e: f"customer-{i}@example.test" for i, e in enumerate(emails, 1)}
    for span in trace["spans"]:  # security codes: take them from verify_identity
        a = span["attributes"]
        if a.get("gen_ai.tool.name") == "verify_identity":
            code = a["gen_ai.tool.call.arguments"]["code"]
            mapping[f"code {code}"] = "code 0000"  # in the request text
            mapping[f'"code": "{code}"'] = '"code": "0000"'  # in the arguments
    mapping |= KNOWN_VALUES
    for real, fake in mapping.items():
        text = text.replace(real, fake)  # same value, same placeholder everywhere
    leftover = EMAIL.findall(text.replace("@example.test", ""))
    assert not leftover, f"unredacted emails: {leftover}"
    return json.loads(text)


if __name__ == "__main__":
    clean = redact_trace(json.load(open("prod_trace.json")))
    with open("trace_redacted.json", "w") as f:
        json.dump(clean, f, indent=1, ensure_ascii=False)
    print("wrote trace_redacted.json")
Terminal
python3 redact.py && python3 read_trace.py trace_redacted.json | head -5
Expected output
wrote trace_redacted.json
trace 4bf92f35 agent v2
user      Hi, it's Customer One ([email protected]), code 0000. Order 1005
          arrived fine, but order 1006 is broken. Please refund order 1006.
lookup_customer {'email': '[email protected]'}
          -> {'customer_id': 'C-7'}

04. Step 3: Build the task from the trace

A task needs an initial state, a request and checks, and each comes from a different place. The request is the user message in the first span. Part of the initial state comes from the recorded tool results: the customer and order 1005 become rows of the mock backend, exactly as the tools returned them. The rest does not appear in the trace, because the agent never read order 1006; a trace shows only what the agent looked at. Someone copies that row from the order database, redacted. The checks cannot come from the trace at all. The trace records what happened, and a person who read the complaint writes down what should have happened.

Python · evalsuite/trace_to_task.py
"""Turn a redacted production trace into a regression task with mocked state."""
import json

trace = json.load(open("trace_redacted.json"))
spans = [s["attributes"] for s in trace["spans"]]
request = spans[0]["gen_ai.input.messages"][0]["parts"][0]["content"]
calls = {a["gen_ai.tool.name"]: a for a in spans if "gen_ai.tool.name" in a}

# 1. State the agent saw, rebuilt from the recorded tool calls and results.
customer = calls["lookup_customer"]["gen_ai.tool.call.result"]["customer_id"]
email = calls["lookup_customer"]["gen_ai.tool.call.arguments"]["email"]
code = calls["verify_identity"]["gen_ai.tool.call.arguments"]["code"]
seen = calls["get_order"]["gen_ai.tool.call.result"]
orders = [[seen["order_id"], seen["customer_id"], seen["total_pence"], seen["status"]]]

# 2. State the agent never read: copied by hand from the order database.
orders.append(["1006", customer, 5400, "delivered"])

# 3. The expected outcome, written by the person who read the complaint.
checks = [["refunded", "1006", 5400], ["refunded", "1005", 0]]

task = {"id": "refund-named-order", "source_trace": trace["trace_id"],
        "initial_state": {"customers": [[customer, email, code]],
                          "orders": orders, "refunds": []},
        "request": request, "checks": checks}
with open("regression_tasks.json", "w") as f:
    json.dump([task], f, indent=1, ensure_ascii=False)
print("task", task["id"], "from trace", task["source_trace"][:8])
print("  orders:", ", ".join(f"{o[0]} ({o[2]} pence)" for o in orders))
print("  checks:", checks)
Terminal
python3 trace_to_task.py
Expected output
task refund-named-order from trace 4bf92f35
  orders: 1005 (3200 pence), 1006 (5400 pence)
  checks: [['refunded', '1006', 5400], ['refunded', '1005', 0]]

05. Step 4: See it fail, then fix and see it pass

A regression task that passes on the buggy version protects nothing, so run it on v2 first. The fix, v3, takes the order the customer asks to refund or cancel. The runner also reruns the six original tasks, because a fix can break something else.

Python · evalsuite/fixed_client.py
"""v3: the fix. Use the order the customer asks to refund or cancel, not the
first order number in the message."""
import re

from fake_client import FakeClient


class FixedClient(FakeClient):
    def pick_order_id(self, request: str) -> str:
        named = re.search(r"(?:refund|cancel) order (\d{4})", request, re.I)
        return named[1] if named else super().pick_order_id(request)
Python · evalsuite/run_regression.py
"""Run the regression task (and the original suite) against an agent version."""
import json
import sys

from fake_client import FakeClient
from fixed_client import FixedClient
from runner import run_task
from tasks import TASKS

CLIENTS = {"v2": lambda: FakeClient("v2"), "v3": FixedClient}
version = sys.argv[1]
regression = json.load(open("regression_tasks.json"))
for task in regression + TASKS:
    result = run_task(task, CLIENTS[version]())
    print(f"{'PASS' if result['passed'] else 'FAIL'}  {task['id']}")
    for failure in result["failures"]:
        print(f"      check failed: {failure}")
Terminal
python3 run_regression.py v2 | head -3 && python3 run_regression.py v3
Expected output
FAIL  refund-named-order
      check failed: refunded(1006) = 0, expected 5400
      check failed: refunded(1005) = 3200, expected 0
PASS  refund-named-order
PASS  refund-broken
PASS  cancel-pending
PASS  partial-refund
PASS  wrong-code
PASS  not-their-order
PASS  cancel-delivered

With a real model, the fix would be a change to the prompt, a tool description or a tool, for example an instruction to confirm the order number with the customer when a message names more than one. A line in the system prompt such as "double-check order numbers" may or may not hold; the task is what tells you.

06. Step 5: Run the suite in CI, in tiers

With a real model every task costs model calls, and a full suite with five trials per task can take hours. So most teams run it in tiers. On each pull request, a fast tier runs a fixed subset: the must-pass regression tasks and a few core tasks, with one or a few trials. Nightly and before every release, the full tier runs every task with several trials. Anything random in the harness, such as generated fixtures, simulated users or a stochastic stand-in, uses fixed seeds. Then every pull request is measured on the same tasks under the same conditions; a random sample that changes every time makes results impossible to compare.

ci_eval.py runs one tier and saves every outcome. gate.py applies two agreed rules, every must-pass task passes in every trial and the pass rate stays above the tier's floor, and exits with status 1 when one breaks, which is all CI needs to fail the job. The thresholds live in reviewed code, so lowering one to get a change merged is visible.

Python · evalsuite/ci_eval.py
"""Run one CI tier and save every outcome; gate.py decides pass or fail."""
import argparse
import json

from fake_client import FakeClient
from fixed_client import FixedClient
from runner import run_task
from tasks import TASKS

TIERS = {  # a FIXED subset for pull requests, so results compare between PRs
    "pr": {"tasks": ["refund-named-order", "partial-refund", "wrong-code"],
           "trials": 1},
    "nightly": {"tasks": None, "trials": 5},  # None: every task
}
MUST_PASS = ["refund-named-order", "wrong-code", "not-their-order"]
CLIENTS = {"v2": lambda: FakeClient("v2"), "v3": FixedClient}

parser = argparse.ArgumentParser()
parser.add_argument("--tier", choices=TIERS, required=True)
parser.add_argument("--agent", choices=CLIENTS, required=True)
args = parser.parse_args()
tier = TIERS[args.tier]
suite = json.load(open("regression_tasks.json")) + TASKS
chosen = [t for t in suite if tier["tasks"] is None or t["id"] in tier["tasks"]]
outcomes = [{"id": t["id"], "trial": n,
             "passed": run_task(t, CLIENTS[args.agent]())["passed"]}
            for t in chosen for n in range(tier["trials"])]
report = {"tier": args.tier, "agent": args.agent, "must_pass": MUST_PASS,
          "outcomes": outcomes}
with open(f"results-{args.tier}-{args.agent}.json", "w") as f:
    json.dump(report, f, indent=1)
print(f"{args.tier}: {len(chosen)} tasks x {tier['trials']} trials ="
      f" {len(outcomes)} runs -> results-{args.tier}-{args.agent}.json")
Python · evalsuite/gate.py
"""Fail the CI job (exit code 1) when the results break an agreed rule."""
import json
import sys

FLOOR = {"pr": 1.00, "nightly": 0.95}  # agreed in review, not tuned per PR

report = json.load(open(sys.argv[1]))
outcomes = report["outcomes"]
rate = sum(o["passed"] for o in outcomes) / len(outcomes)
problems = []
for task_id in report["must_pass"]:
    runs = [o["passed"] for o in outcomes if o["id"] == task_id]
    if runs and not all(runs):
        problems.append(f"must-pass task {task_id} failed {runs.count(False)}"
                        f" of {len(runs)} runs")
if rate < FLOOR[report["tier"]]:
    problems.append(f"pass rate {rate:.2f} is below the floor"
                    f" {FLOOR[report['tier']]:.2f}")
print(f"gate ({report['tier']}, agent {report['agent']}): pass rate {rate:.2f}")
for problem in problems:
    print("  FAIL:", problem)
print("  result:", "blocked" if problems else "passed")
sys.exit(1 if problems else 0)
Terminal
python3 ci_eval.py --tier pr --agent v2 && python3 gate.py results-pr-v2.json
echo "exit code: $?"
python3 ci_eval.py --tier nightly --agent v3 && python3 gate.py results-nightly-v3.json
echo "exit code: $?"
Expected output
pr: 3 tasks x 1 trials = 3 runs -> results-pr-v2.json
gate (pr, agent v2): pass rate 0.67
  FAIL: must-pass task refund-named-order failed 1 of 1 runs
  FAIL: pass rate 0.67 is below the floor 1.00
  result: blocked
exit code: 1
nightly: 7 tasks x 5 trials = 35 runs -> results-nightly-v3.json
gate (nightly, agent v3): pass rate 1.00
  result: passed
exit code: 0

The PR tier blocks v2 on the regression task; the nightly tier passes v3 on all 35 runs. Here five trials give the same result because the stand-in is deterministic; with a real model, the nightly trials are what reveal a task that passes only some of the time. The CI regression gate lab shows the GitHub Actions workflow around a gate like this, with secrets and a committed baseline.

07. Step 6: Online evaluation on sampled traffic

The offline suite covers the cases you thought of. Production finds the others; this one surfaced only because a customer wrote in. Online evaluation grades a sample of production traces continuously, usually with a model grader calibrated as in lesson 3, so that failures surface without waiting for complaints. The sample should be repeatable and independent of the content: hashing the trace ID with a salt gives the same decision for the same trace every time.

Python · evalsuite/online_sample.py
"""Choose a repeatable 2% sample of production traces for the online grader."""
import hashlib

SALT = "online-eval-v1"  # change the salt to draw a fresh, independent sample


def sampled(trace_id: str, rate: float = 0.02) -> bool:
    digest = hashlib.sha256((SALT + trace_id).encode()).hexdigest()
    return int(digest[:8], 16) / 0x100000000 < rate  # same id, same decision


day = [f"trace-{n:05d}" for n in range(5000)]  # one day of trace ids
picked = [t for t in day if sampled(t)]
print(f"{len(picked)} of {len(day)} traces sampled; first three: {picked[:3]}")
Terminal
python3 online_sample.py
Expected output
99 of 5000 traces sampled; first three: ['trace-00018', 'trace-00028', 'trace-00071']

Treat the online grader's output as a signal to investigate, not a verdict. When its flagged rate rises after a release, read the flagged traces, confirm which are real failures (the grader can be wrong both ways), fix the cause, and turn each confirmed failure into a regression task as in steps 2 to 4, so the next CI run catches it. Do not raise the grader's threshold until the rate looks normal again: that hides a regression. If the traces show the grader itself is wrong, recalibrate it against fresh expert labels. The trace and error analysis lab shows this sampling and reading in detail.

08. Step 7: When to use a harness such as Inspect

The harness in these labs fits in a few hundred lines, so every part is visible. As a suite grows, a framework saves work. Inspect, from the UK AI Security Institute and Meridian Labs, is one open-source example. An Inspect task combines a dataset of samples, a solver or agent, and a scorer, which map onto TASKS, run_agent() and the checks here. It supports custom and MCP tools, sandboxes such as Docker where each sample gets its own instance, epochs for repeated trials, and a log viewer (inspect view). Public benchmarks such as tau-bench help compare models, but they test someone else's tools and policies, so your own suite stays the basis for release decisions.

09. Check your understanding

Practice check · 3 questions

From trace to task

Answer from the code and output of this lesson.

Q1. Why does `trace_to_task.py` add order 1006 by hand instead of reading it from the trace?
Q2. Before writing `fixed_client.py`, you run the new task on v2 (the stand-in is deterministic) and it prints PASS. What does that tell you?
Q3. Why does `online_sample.py` hash the trace ID with a salt instead of calling `random.random()` for each trace?
Practice only: not graded, not saved, not evidence.

10. Apply it

For the practice project, wire your 25-task suite into CI: a PR tier with your must-pass tasks and a fixed list of core tasks, a nightly tier with every task and 5 trials, and a gate that fails the job when a must-pass task fails in any trial or the pass rate drops below an agreed floor. Then take one real failed trace of your agent (from staging if you have no production yet), redact it, turn it into a task, and show in the pull request that it fails before your fix and passes after it.

11. Review prompt

Without looking back: name the three sources of a regression task built from a trace, and say which one a person must write. Explain why you redact before storing, and why the task must first fail on the buggy version. Describe the two CI tiers and why the PR subset is fixed. Then say what to do, and what not to do, when an online grader's flagged rate rises after a release.

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