11A.3 Latency Percentiles, Error Classification, Audit Logs, Session Replay, Dashboards and SLOs
With traces flowing (11A.1, including the GenAI conventions in 3.7 to 3.13) and the metrics pipeline of 11A.2 in place, you can start running an agent like a service. This lesson goes deeper than 11A.2 on the numbers and records that make an agent accountable: how to measure the latency of a run that has many steps, how to sort failures into a small set of causes, how to keep a tamper-evident record of what an agent did and replay a session, and how to turn all of it into dashboards, service level objectives (SLOs) and alerts that page you for the right reasons. Everything runs offline in plain Python.
What you'll learn
- Per-step versus per-run latency, time to first token, and why averages hide the problem
- How to compute p50, p95 and p99 correctly (nearest-rank and interpolation), and the mistakes to avoid when combining them
- A small error taxonomy for agents (provider limits and errors, timeouts, tool errors, validation, refusals, budget stops, loop stops) and a classifier
- How to monitor retries: attempts, amplification and give-ups, and how to detect a retry storm
- Audit logs: what to record for every agent action, and a tamper-evident hash chain
- Session replay: what to record so you can re-run a session without a model or side effects, and what to redact
- Agent SLIs and SLOs (task success, cost per successful task, p95 run latency, escalation rate) and multi-window burn-rate alerts
What you don't need
- API keys, a model, or a metrics backend. The data is simulated with seeded random numbers and the code is standard library only; the output you see is real.
- Prometheus or Grafana. 11A.2 builds those and owns the SLO document, the alert rules and the dashboards as code; this lesson stays with the logic and links there for the tooling.
- A legal opinion. Audit-log retention and access rules are mentioned as design questions, not advice.
Setup
Python 3.11 or newer and the standard library. As of 1 December 2026 nothing to install. Save each block under the name in its first comment.
What you must be able to do after this lesson#
- Compute p50, p95 and p99 of run latency from step data, and explain why averaging percentiles gives a wrong answer
- Classify every agent failure into a small taxonomy and count retry amplification and give-up rate over short windows
- Build an append-only audit log with a hash chain, verify it, and explain what anchoring the head hash adds
- Record a session at the model and tool boundary and replay it with no model call and no side effects
- Evaluate multi-window burn-rate alerts for an agent SLO and say when each one fires and resolves
- Choose dashboard panels and alerts for an agent that page on symptoms and ticket on trends
Why this matters for an AI engineer#
A single chat request has one model call and one latency. An agent run has between one and fifty steps, each with its own latency, and failures can happen anywhere. The numbers you learned for web services (average latency, error rate) mislead when applied naively. And an agent that takes real actions (refunds, emails, deployments) needs an accountable record of what it did, not just a trace for debugging.
| You'll hear... | You'll understand it after... |
|---|---|
| "Average latency is fine, why are users complaining?" | 1.2 Why averages lie |
| "What's our p95 for a whole run?" | 1.1 and 1.3 |
| "Are those 429s or our bug?" | Part 2: Errors |
| "Prove the agent did not issue that refund." | Part 3: Audit logs |
| "Can we replay the session that failed?" | 3.4 Session replay |
| "What should we page on?" | Part 4 |
Part 1: Latency percentiles for multi-step runs#
11A.2, 1.3 and 2.3 say that duration is a distribution and show how to pick histogram buckets. Here you work out run latency from step latency, and see where percentile arithmetic goes wrong.
1.1 Per-step, per-run and time to first token#
Three latencies matter, and they answer different questions.
| Latency | What it is | Who feels it | Where it comes from |
|---|---|---|---|
| Step latency | One model call, or one tool call | Engineers tuning a model or a tool | The chat and execute_tool spans (11A.1, 3.7) |
| Run latency | From the user's request to the agent's final answer | The user waiting for the result | The invoke_agent span (the OTel agent metric is gen_ai.invoke_agent.duration, see 11A.1, 3.13) |
| Time to first token (TTFT) | Request sent to first streamed token | The user, as "is it alive?" | gen_ai.response.time_to_first_chunk on streaming chat spans |
For agents, run latency is not step latency times a constant, because the number of steps varies from run to run. A run with one step is fast. A run that needs eight steps is eight times the model time plus eight tool calls plus any retries. The distribution of step counts is itself a source of latency tails.
Also separate waiting from working. A step can be slow because the model is slow, because you waited for a rate-limit back-off, or because a tool was slow. The span tree lets you split a run's time into those parts: add up the chat spans, add up the execute_tool spans, and what remains is time spent in your own code or waiting.
1.2 Why averages lie#
The script below simulates 5,000 agent runs. Steps per run vary from 1 to 12, model calls have a log-normal latency (many fast, some slow), 4% of calls hit a provider rate limit and wait, and 70% of steps also call a tool. It prints the mean and the percentiles for steps and for whole runs. The seeded random numbers make the output reproducible; the numbers themselves are simulated, not measured from a real provider.
# percentiles.py (standard library only)
import math
import random
import statistics
def percentile_nearest_rank(values, p):
"""The smallest value such that at least p% of the data is <= it. Always returns a real observation."""
xs = sorted(values)
rank = max(1, math.ceil(p / 100 * len(xs)))
return xs[rank - 1]
def percentile_linear(values, p):
"""Interpolate between the two nearest observations (the common 'inclusive' method)."""
xs = sorted(values)
pos = p / 100 * (len(xs) - 1)
lo, hi = math.floor(pos), math.ceil(pos)
return xs[lo] + (xs[hi] - xs[lo]) * (pos - lo)
def simulate_run(rng):
"""One agent run: 1 to 12 model steps; each step = model call (+ tool call); sometimes a 429 retry."""
steps = 1
while steps < 12 and rng.random() < 0.6:
steps += 1
step_times = []
for _ in range(steps):
t = rng.lognormvariate(math.log(1.4), 0.55) # model call, seconds
if rng.random() < 0.04:
t += rng.uniform(2, 8) # provider 429 then back-off, then success
if rng.random() < 0.7:
t += rng.lognormvariate(math.log(0.15), 0.6) # tool call
step_times.append(t)
return step_times
rng = random.Random(7)
runs = [simulate_run(rng) for _ in range(5000)]
steps = [t for r in runs for t in r]
totals = [sum(r) for r in runs]
print(f"{'':<10}{'n':>7}{'mean':>8}{'p50':>8}{'p95':>8}{'p99':>8} (seconds, nearest-rank)")
for label, data in (("per step", steps), ("per run", totals)):
print(f"{label:<10}{len(data):>7}{statistics.mean(data):>8.2f}"
f"{percentile_nearest_rank(data, 50):>8.2f}{percentile_nearest_rank(data, 95):>8.2f}"
f"{percentile_nearest_rank(data, 99):>8.2f}")
avg_steps = statistics.mean(len(r) for r in runs)
naive = avg_steps * percentile_nearest_rank(steps, 95)
print(f"\naverage steps per run: {avg_steps:.2f}")
print(f"'step p95 x average steps' = {naive:.1f} s vs true run p95 = {percentile_nearest_rank(totals, 95):.1f} s")
print("\nShare of runs by step count (why the run distribution is wide):")
for k in (1, 2, 3, 5, 8, 12):
share = sum(1 for r in runs if len(r) == k) / len(runs)
print(f" {k:>2} steps: {share:6.1%}")
small = [1.2, 1.3, 1.1, 1.4, 1.2, 1.5, 1.3, 1.2, 1.6, 9.8]
print("\nTen observations, one slow:", small)
for p in (50, 90, 95, 99):
print(f" p{p}: nearest-rank={percentile_nearest_rank(small, p):5.2f} linear={percentile_linear(small, p):5.2f}")
# Averaging percentiles is wrong: two hosts, very different traffic.
busy = [rng.lognormvariate(0, 0.3) for _ in range(9000)]
quiet = [rng.lognormvariate(1.2, 0.3) for _ in range(300)]
avg_of_p95 = (percentile_nearest_rank(busy, 95) + percentile_nearest_rank(quiet, 95)) / 2
print(f"\nmean of two hosts' p95 = {avg_of_p95:.2f} s; p95 of all requests together = "
f"{percentile_nearest_rank(busy + quiet, 95):.2f} s") n mean p50 p95 p99 (seconds, nearest-rank)
per step 12279 1.96 1.58 4.61 8.28
per run 5000 4.82 3.36 13.59 20.47
average steps per run: 2.46
'step p95 x average steps' = 11.3 s vs true run p95 = 13.6 s
Share of runs by step count (why the run distribution is wide):
1 steps: 41.3%
2 steps: 23.8%
3 steps: 13.9%
5 steps: 5.2%
8 steps: 0.9%
12 steps: 0.4%
Ten observations, one slow: [1.2, 1.3, 1.1, 1.4, 1.2, 1.5, 1.3, 1.2, 1.6, 9.8]
p50: nearest-rank= 1.30 linear= 1.30
p90: nearest-rank= 1.60 linear= 2.42
p95: nearest-rank= 9.80 linear= 6.11
p99: nearest-rank= 9.80 linear= 9.06
mean of two hosts' p95 = 3.43 s; p95 of all requests together = 1.88 sRead it row by row.
- Per step, the mean is 1.96 s but the p99 is 8.28 s: one step in a hundred takes four times the average.
- Per run, the mean is 4.82 s and the median 3.36 s, but the p95 is 13.59 s. The mean is pulled up by the long runs and is not what a typical user experiences. The p50 is the typical run; the p95 is what a user who has a bad day sees.
- You cannot get run latency from step latency. "Step p95 times average steps" gives 11.3 s; the true run p95 is 13.6 s. The tail of the run distribution comes from long runs, which are made of many steps, which each have their own tails.
- The step-count table shows why: 41% of runs have one step, but a long tail reaches 12.
1.3 Computing percentiles#
The same script contains two ways to compute a percentile. With many observations they agree; with few they do not, so know which you use.
- Nearest-rank: sort the data; the p-th percentile is the value at rank
ceil(p/100 × n). It always returns a value that was actually observed. Simple and what many dashboards mean. - Linear interpolation: place p on the sorted list between the two nearest observations and interpolate. Smoother, and may return a number that never occurred.
On ten observations with one slow outlier (the script's second table), p50 is the same for both, but p90 is 1.60 s with nearest-rank and 2.42 s with interpolation, and p95 is 9.80 s versus 6.11 s. With ten data points, p95 is "the slowest one". A percentile with few observations is mostly noise, so show the sample size next to it, and do not alert on p99 over a window with only 50 requests.
Three mistakes to avoid:
- Averaging percentiles. The last block of the script has a busy host (9,000 requests) and a quiet slow one (300). The mean of their two p95 values is 3.43 s, but the p95 of all requests together is 1.88 s. You cannot combine percentiles by averaging, because percentiles ignore how many requests each came from. Combine the raw observations, or combine histograms (bucket counts add up; percentiles are estimated afterwards).
- Histogram buckets that do not fit. A percentile estimated from a histogram is only as good as its bucket edges. 11A.2, 2.3 has the bucket advice and the streaming two-histogram pattern.
- Mixing populations. A chat reply and a long-running research run have different latency profiles. Compute percentiles per route, feature or tier. A single global p95 mixes them and describes neither.
Part 2: Error classification and retry monitoring#
03.8 classifies what a provider call returned (11A.2, 1.2 counts those classes), and 08A.14, 1.2 lists the ways an agent design fails. This part adds a small taxonomy for a whole agent step, built for counting and alerting, then watches retries over short windows. 01B.9, 1.3 explains why retries amplify; the simulation shows what it looks like.
2.1 A taxonomy of agent failures#
"Error rate" as a single number is almost useless for agents, because the causes need different responses. A provider outage needs a fallback; a validation failure needs a prompt fix; a budget stop is your own system working as designed. Sort every failure into one class, so you can count and alert per class.
| Class | What happened | Typical response |
|---|---|---|
provider_rate_limit |
HTTP 429 from the model provider | Back off, spread load, check quotas |
provider_server |
HTTP 5xx, or "overloaded" (Anthropic documents 529) | Retry, then fall back to another model or provider |
timeout |
No answer within your deadline | Retry with a cap, check deadlines |
tool_error |
A tool raised, or returned an error result | Fix the tool; check the arguments the model sent |
validation |
Output or arguments failed schema validation | Fix the prompt or schema; consider a repair step |
refusal |
The model declined (refusal or content-filter stop) | Review: is it a wrong refusal? |
budget_stop |
Your step, token, cost or time budget ended the run | Tune budgets; look for waste |
loop_stop |
Your loop detector ended the run | Look at the repeated calls |
other |
Not classified | Keep this small; review it weekly |
Two notes. First, a 429 can mean "slow down" or "you are out of quota or money", and only the first should be retried; 03.8, 4.2 and the classifier in 03.8, 4.4 go deeper than the one class here. Second, budget_stop and loop_stop are not errors from the user's point of view in the same way, but they are failures to complete the task, so they count against a task-success SLO (Part 4) while being different from provider failures. The OTel convention for the span is error.type (11A.1, 3.8); your class names can be the values you put there.
2.2 Classifying and watching retries#
The script below has a classify function, then simulates a day of 4,320 model calls with an incident in the middle (40 minutes where the provider fails more than half the time). Each call has a retry budget of four attempts. It reports retry amplification: total attempts divided by logical calls.
# errors_retries.py (standard library only)
"""Classify every failure into a small, stable taxonomy, and watch retries."""
import random
from collections import Counter
# One class per *cause you would act on differently*.
TAXONOMY = {
"provider_rate_limit": "HTTP 429 from the model provider",
"provider_server": "HTTP 5xx or overloaded from the model provider",
"timeout": "no answer within our deadline",
"tool_error": "a tool raised or returned an error result",
"validation": "output or arguments failed schema validation",
"refusal": "the model declined (stop reason: refusal / content filter)",
"budget_stop": "our own step, token, cost or time budget ended the run",
"loop_stop": "our loop detector ended the run",
"other": "anything we could not classify (keep this class small and review it)",
}
def classify(*, http_status=None, exc_name=None, stop_reason=None, tool_failed=False, schema_ok=True):
if stop_reason in ("budget_exhausted",):
return "budget_stop"
if stop_reason == "loop_detected":
return "loop_stop"
if stop_reason in ("refusal", "content_filter"):
return "refusal"
if http_status == 429:
return "provider_rate_limit"
if http_status is not None and http_status >= 500:
return "provider_server"
if exc_name in ("TimeoutError", "ReadTimeout", "APITimeoutError"):
return "timeout"
if tool_failed:
return "tool_error"
if not schema_ok:
return "validation"
return "other" if (http_status or exc_name or stop_reason) else "ok"
assert classify(http_status=429) == "provider_rate_limit"
assert classify(http_status=529) == "provider_server"
assert classify(exc_name="ReadTimeout") == "timeout"
assert classify(stop_reason="loop_detected") == "loop_stop"
assert classify() == "ok"
# --- a day of calls, each with its attempt history -----------------------------------
rng = random.Random(3)
def one_call(minute):
"""Return the list of attempt outcomes for one logical model call."""
storm = 600 <= minute < 640 # a 40-minute provider incident
p_fail = 0.55 if storm else 0.02
attempts = []
while True:
if rng.random() < p_fail:
attempts.append(classify(http_status=429 if rng.random() < 0.7 else 503))
if len(attempts) == 4: # retry budget: 4 attempts, then give up
return attempts
else:
attempts.append("ok")
return attempts
calls = [(m, one_call(m)) for m in range(24 * 60) for _ in range(3)]
def report(label, rows):
n = len(rows)
attempts = sum(len(a) for _, a in rows)
retried = sum(1 for _, a in rows if len(a) > 1)
gave_up = sum(1 for _, a in rows if a[-1] != "ok")
causes = Counter(c for _, a in rows for c in a if c != "ok")
print(f"{label:<12} calls={n:<5} attempts={attempts:<5} amplification={attempts / n:.2f}x "
f"retried={retried / n:5.1%} gave_up={gave_up / n:5.1%} causes={dict(causes)}")
report("whole day", calls)
report("incident", [(m, a) for m, a in calls if 600 <= m < 640])
report("normal", [(m, a) for m, a in calls if not 600 <= m < 640])
# A retry-storm alert: amplification over a 10-minute window above a threshold.
window = 10
for start in range(0, 24 * 60, window):
rows = [a for m, a in calls if start <= m < start + window]
amp = sum(len(a) for a in rows) / len(rows)
if amp > 1.5:
print(f"ALERT minute {start:>4}-{start + window}: retry amplification {amp:.2f}x")whole day calls=4320 attempts=4527 amplification=1.05x retried= 3.5% gave_up= 0.3% causes={'provider_server': 73, 'provider_rate_limit': 145}
incident calls=120 attempts=241 amplification=2.01x retried=55.0% gave_up= 9.2% causes={'provider_server': 53, 'provider_rate_limit': 79}
normal calls=4200 attempts=4286 amplification=1.02x retried= 2.0% gave_up= 0.0% causes={'provider_server': 20, 'provider_rate_limit': 66}
ALERT minute 600-610: retry amplification 2.00x
ALERT minute 610-620: retry amplification 1.90x
ALERT minute 620-630: retry amplification 2.13x
ALERT minute 630-640: retry amplification 2.00xWhat the numbers say:
- Over the whole day, amplification is 1.05x and 3.5% of calls were retried. That looks harmless.
- During the incident, amplification is 2.01x, 55% of calls were retried and 9.2% of calls gave up after four attempts. The day-long average hides a 40-minute outage.
- The alert fires on a 10-minute window, because a window short enough to catch an incident is the only one that shows it.
What to monitor about retries. 03.8, 13.6 lists the per-call measures (attempts per call, retry rate, 429 share, timeout rate). This lesson adds four that only show up over time:
- Amplification over a short window, as in the script: it is the earliest sign of an incident, and it is also how much extra load and cost your retries add, which in an outage can make things worse.
- Give-up rate: calls that exhausted their retries. This is what the user actually felt.
- Added latency from retries: retries are part of why the run p95 grows. Record each attempt as its own span with an
attemptattribute, so the trace shows the waiting. - Who retries: the SDK, your wrapper, or both. A double retry multiplies attempts (03.8, 5.5; 03.8, 7.4 covers retry budgets).
Part 3: Audit logs and session replay#
Deep-dive
12.6, Part 8 defines the audit record for tool calls, and 08A.14, 7.4 says an audit log must be append-only and tamper-evident. This part builds the hash chain that makes tampering detectable (with its limits), and a record and replay wrapper at the model and tool boundary.
3.1 Audit log versus trace#
They look similar and have different jobs.
| Trace | Audit log | |
|---|---|---|
| Purpose | Debug and measure | Accountability: who or what did what, and who allowed it |
| Records | Everything, including model calls | Actions with side effects and the decisions around them (allowed, denied, approved) |
| Content | May contain prompts if capture is on | Minimal: ids, action, target, decision, a hash of the arguments |
| Loss tolerance | Sampling and loss are acceptable | Must not silently lose or change records |
| Integrity | Not needed | Tamper-evident: you can show it was not edited |
| Retention | Short (days to weeks) | Set by policy, often longer |
| Access | Engineers | A small, controlled group |
An agent that can issue refunds should write an audit record when it calls the tool, when a human approves, and when the action executes. The record does not need the full conversation. It needs enough to answer "who, what, when, allowed by whom".
3.2 What to record for an agent action#
12.6, 8.1 has the full list of what an audit record must answer: who, what (with the arguments hashed), when, the decision and approver, the outcome, and a correlation id. This lesson's records add two things the chain in 3.3 needs, and keep everything else small:
- Order and time:
seqandts. - Chain links:
prev_hashandhash(3.3). - Ids, not names:
actorisagent:support-1orhuman:ana.decisionis one ofallowed,needs_approval,approved,denied,executed. - A hash of the arguments, not the arguments:
args_hashis the SHA-256 of the canonical arguments, so the record proves which arguments were used without storing them. If an auditor must see the amount, the arguments live in the system of record (the refund table) and the audit log points to it. - A
trace_idso an auditor can find the debugging detail, subject to the trace's own retention.
Keep personal data out: store a hash or an id, not the customer's address.
3.3 A tamper-evident hash chain#
A hash chain makes each record commit to the one before it: record n stores the hash of record n−1, and its own hash covers everything including that link. If anyone edits or deletes an earlier record, the later hashes no longer match, and a verifier can say exactly where. It is the idea behind a blockchain without the network.
# audit_chain.py (standard library only)
"""An append-only audit log where each record commits to the one before it (a hash chain)."""
import hashlib
import json
import os
import tempfile
GENESIS = "0" * 64
def canonical(obj):
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
def sha256(text):
return hashlib.sha256(text.encode("utf-8")).hexdigest()
class AuditLog:
def __init__(self, path):
self.path = path
self.prev = GENESIS
self.seq = 0
if os.path.exists(path): # resume an existing chain
for line in open(path, encoding="utf-8"):
rec = json.loads(line)
self.prev, self.seq = rec["hash"], rec["seq"] + 1
def append(self, *, actor, action, target, decision, args=None, details=None):
body = {"seq": self.seq, "ts": 1_700_000_000 + self.seq * 7, # fixed clock keeps the demo reproducible
"actor": actor, "action": action, "target": target, "decision": decision,
"args_hash": sha256(canonical(args)) if args is not None else None, # hash, not the values
"details": details or {}, "prev_hash": self.prev}
body["hash"] = sha256(canonical(body))
with open(self.path, "a", encoding="utf-8") as f:
f.write(canonical(body) + "\n")
self.prev, self.seq = body["hash"], self.seq + 1
return body
def verify(path):
"""Return (ok, message). Recompute every hash and check every link."""
prev = GENESIS
for i, line in enumerate(open(path, encoding="utf-8")):
rec = json.loads(line)
claimed = rec.pop("hash")
if rec["prev_hash"] != prev:
return False, f"record {i}: chain broken (prev_hash does not match record {i - 1})"
if sha256(canonical(rec)) != claimed:
return False, f"record {i}: contents changed (hash mismatch)"
prev = claimed
return True, f"{i + 1} records, chain intact, head={prev[:12]}..."
if __name__ == "__main__":
path = os.path.join(tempfile.mkdtemp(), "audit.jsonl")
log = AuditLog(path)
log.append(actor="agent:support-1", action="tool_call", target="lookup_order", decision="allowed",
args={"order_id": "A17"})
log.append(actor="agent:support-1", action="tool_call", target="issue_refund", decision="needs_approval",
args={"order_id": "A17", "amount": 84.50}, details={"risk": "high"})
log.append(actor="human:ana", action="approval", target="issue_refund", decision="approved",
details={"ticket": "T-4471"})
log.append(actor="agent:support-1", action="tool_call", target="issue_refund", decision="executed",
args={"order_id": "A17", "amount": 84.50}, details={"result": "ok"})
print(verify(path)[1])
lines = open(path, encoding="utf-8").read().splitlines()
tampered = json.loads(lines[2])
tampered["decision"] = "denied" # someone edits history
lines[2] = canonical(tampered)
open(path, "w", encoding="utf-8").write("\n".join(lines) + "\n")
print("after editing record 2:", verify(path)[1])
lines = [l for i, l in enumerate(open(path, encoding="utf-8").read().splitlines()) if i != 1]
open(path, "w", encoding="utf-8").write("\n".join(lines) + "\n")
print("after deleting record 1:", verify(path)[1])
# Truncating the tail is invisible to the chain itself: keep the head hash somewhere else.
print("\nhead hash must be anchored outside the file (a ticket, a write-once bucket, a second system).")Output (the script uses a fixed clock so the head hash is reproducible on your machine):
4 records, chain intact, head=64b5eb489f00...
after editing record 2: record 2: contents changed (hash mismatch)
after deleting record 1: record 1: chain broken (prev_hash does not match record 0)
head hash must be anchored outside the file (a ticket, a write-once bucket, a second system).The verifier recomputes every hash. Editing record 2 (changing approved to denied) was caught at record 2 as a content change. Deleting record 1 was caught as a broken link. Note what the chain does not do:
- It does not stop tampering. Anyone with write access can still change the file. It makes tampering detectable.
- It cannot detect truncation of the tail. If someone deletes the last records, the remaining chain is still valid. The fix is to anchor the head hash somewhere the writer cannot edit: a write-once storage bucket, a second system, or a periodic entry in a ticket. Verifying later means "the chain from the file reaches the anchored head".
- It does not make the content true. It proves the record was not changed after it was written, not that the agent wrote an honest record. Write the record in your code, not from the model's text.
- A rewritten log with a valid chain is possible if the attacker recomputes all hashes and you have no anchor. Anchoring is what closes that gap.
3.4 Session replay#
Session replay means re-running a recorded session to see what the agent did, without calling the model or running tools again. 08A.14, 5.4 explains the idea and its eval-harness form; here is the recorder that produces the recording. It serves three purposes: debugging ("show me exactly what happened"), regression testing ("does my new code still make the same decisions on that session?") and review.
To replay, record at the boundary where your agent meets the outside world, because that is where the non-determinism lives:
| Record | Why |
|---|---|
| Every model response (text, tool calls, finish reason) | The model is not deterministic; replay serves the recorded answer |
| Every tool call and result | Replay must not repeat side effects, and the world may have changed |
| The inputs to each model call, or enough to rebuild them | To check the agent made the same request |
| Versions: prompt version, model id and resolved model, tool schema, code version | A replay on different code is a different experiment |
| Parameters: temperature, max tokens, budgets | Behaviour depends on them |
| Clock and ids if your code uses them | Otherwise replay will differ for boring reasons |
The script below records a live session with a scripted model and a refund tool, then replays it twice: once on the same code, once on changed code.
# replay.py (standard library only)
"""Record a session, then replay it without any model or tool: same decisions, no side effects."""
import json
class Recorder:
"""Wraps the real model and tools; appends every input and output to a list."""
def __init__(self, model, tools):
self.model, self.tools, self.events = model, tools, []
def call_model(self, messages):
reply = self.model(messages)
self.events.append({"kind": "model", "n_messages": len(messages), "reply": reply})
return reply
def call_tool(self, name, args):
result = self.tools[name](**args)
self.events.append({"kind": "tool", "name": name, "args": args, "result": result})
return result
class Replayer:
"""Serves recorded outputs in order. Refuses to run a step the recording does not contain."""
def __init__(self, events):
self.events, self.i = events, 0
def _next(self, kind):
ev = self.events[self.i]
assert ev["kind"] == kind, f"step {self.i}: recording has a {ev['kind']} call, code made a {kind} call"
self.i += 1
return ev
def call_model(self, messages):
return self._next("model")["reply"]
def call_tool(self, name, args):
ev = self._next("tool")
assert (ev["name"], ev["args"]) == (name, args), f"step {self.i - 1}: tool call differs from recording"
return ev["result"]
def agent(env):
"""The agent logic under test. It only talks to `env`, so it can be recorded or replayed."""
messages = [{"role": "user", "content": "Refund order A17"}]
reply = env.call_model(messages)
while "tool" in reply:
result = env.call_tool(reply["tool"], reply["args"])
messages.append({"role": "tool", "content": result})
reply = env.call_model(messages)
return reply["text"]
refund_log = []
scripted = iter([{"tool": "issue_refund", "args": {"order_id": "A17", "amount": 84.5}},
{"text": "Refunded 84.50 for order A17."}])
rec = Recorder(model=lambda m: next(scripted),
tools={"issue_refund": lambda order_id, amount: refund_log.append(order_id) or {"ok": True}})
live_answer = agent(rec)
print("live run: ", live_answer, "| refunds issued:", len(refund_log))
session_file = json.dumps(rec.events) # this is what you would store (redacted) per session
replayed = agent(Replayer(json.loads(session_file)))
print("replay: ", replayed, "| refunds issued:", len(refund_log), "(unchanged: replay has no side effects)")
print("identical answer:", replayed == live_answer)
# Now change the agent code: it makes a different tool call. Replay catches the behavioural change.
def agent_v2(env):
reply = env.call_model([{"role": "user", "content": "Refund order A17"}])
env.call_tool("lookup_order", {"order_id": "A17"}) # new first step
return reply.get("text", "")
try:
agent_v2(Replayer(json.loads(session_file)))
except AssertionError as e:
print("code change detected by replay ->", e)live run: Refunded 84.50 for order A17. | refunds issued: 1
replay: Refunded 84.50 for order A17. | refunds issued: 1 (unchanged: replay has no side effects)
identical answer: True
code change detected by replay -> step 1: tool call differs from recordingThe replay returned the same answer, and the refund count stayed at 1: replay has no side effects. When the agent code was changed to make an extra tool call, replay failed at the exact step where the code's behaviour differed from the recording. That is a regression test built from a real session.
Privacy. A replay file contains model inputs and outputs and tool results, which means it contains user content. It needs the strictest rules in this lesson: redact before storing (03.12, Part 5; 11A.1, Part 7), keep it for a short, defined time, restrict who can open it, honour deletion requests, and prefer to replay only sessions the user consented to share (11A.4 covers consent). Where content must not be stored, record hashes and replay only the structure.
Replay is not re-execution. A replay checks your code against a recording. It does not tell you what the model would say today. For that, re-run the inputs against the live model, which is an evaluation (Part 5).
Part 4: Dashboards, alerts and SLOs for agents#
11A.2, Part 4 defines SLIs, SLOs and burn rates, and its 4.8 covers steps per run, tool error rate and cost per run. This part adds the outcome-based agent SLIs, a burn-rate evaluator over run records, and the page-or-ticket choices that go with them.
4.1 SLIs for agents#
11A.2 4.8 already defines steps per run (with the step-cap rate), the tool error rate (SLO-5) and cost per run (SLO-6). These are the SLIs this lesson adds, and how each is judged:
| SLI | Good event | Why it matters for agents |
|---|---|---|
| Task success rate | The run's outcome check passed | The one number users care about. Needs an outcome signal: a state check, a user confirmation or a sampled judge (10A.9) |
| Cost per successful task | Total spend divided by successful runs | Cost per request hides waste on failed runs; this one punishes them (the offline form is 10A.7, 5.6) |
| p95 run latency | A run finishes within the bound for its tier | Run latency, not step latency (Part 1) |
| Escalation rate | The run did not need a human | A rising rate means the agent is giving up or being routed away |
| Retry amplification | Attempts per call near 1 | An outage amplifier (Part 2) |
| Loop-stop and budget-stop rate | Few | Your guardrails firing means something is wrong upstream |
4.2 The agent SLIs, computed#
The script generates three days of simulated runs (about three per minute) with an incident at the end: a bad prompt release that caused 80% of runs to fail for 60 minutes. It computes four SLIs over the whole window, then evaluates multi-window burn-rate alerts at three moments.
# burn_rate.py (standard library only)
"""Agent SLIs from run records, and a multi-window burn-rate evaluator."""
import math
import random
from dataclasses import dataclass
@dataclass
class Run:
minute: int # minutes since the start of the 3-day window
success: bool # the task outcome check passed (judge, state check or user confirmation)
cost_usd: float
seconds: float
escalated: bool # handed to a human
rng = random.Random(11)
INCIDENT = (3 * 24 * 60 - 120, 3 * 24 * 60 - 60) # a bad prompt release: 60 minutes, ending an hour before 'now'
runs = []
for minute in range(3 * 24 * 60):
for _ in range(rng.choice([2, 3, 3, 4])): # ~3 runs per minute
bad = INCIDENT[0] <= minute < INCIDENT[1]
ok = rng.random() > (0.80 if bad else 0.03)
runs.append(Run(minute, ok, rng.lognormvariate(math.log(0.04), 0.5),
rng.lognormvariate(math.log(3.5), 0.6), rng.random() < (0.30 if bad else 0.06)))
NOW = 3 * 24 * 60
def window(rs, minutes, end=NOW):
return [r for r in rs if end - minutes <= r.minute < end]
def p95(xs):
xs = sorted(xs)
return xs[max(1, math.ceil(0.95 * len(xs))) - 1]
# --- four agent SLIs over the whole 3 days ---------------------------------------------
n = len(runs)
ok = [r for r in runs if r.success]
print(f"runs: {n}")
print(f"task success rate : {len(ok) / n:.3%}")
print(f"cost per SUCCESSFUL task: ${sum(r.cost_usd for r in runs) / len(ok):.4f} (all spend / successful runs)")
print(f"cost per run : ${sum(r.cost_usd for r in runs) / n:.4f}")
print(f"p95 run latency : {p95([r.seconds for r in runs]):.2f} s")
print(f"escalation rate : {sum(r.escalated for r in runs) / n:.2%}")
# --- burn rate: how fast are we spending the error budget? -----------------------------
SLO = 0.95 # 95% of runs succeed, over 30 days
BUDGET = 1 - SLO # 5% of runs may fail
def burn(minutes, end=NOW):
w = window(runs, minutes, end)
bad = sum(1 for r in w if not r.success)
return (bad / len(w)) / BUDGET
# (severity, long window, short window, threshold) as in the Google SRE Workbook; see 11A.2 section 4.5
RULES = [("PAGE", 60, 5, 14.4), ("PAGE", 360, 30, 6.0), ("TICKET", 4320, 360, 1.0)]
def evaluate(label, end):
print(f"\n{label}")
for sev, long_m, short_m, thr in RULES:
b_long, b_short = burn(long_m, end), burn(short_m, end)
fire = b_long > thr and b_short > thr
print(f" {sev:<6} long={long_m:>4}m burn={b_long:6.2f} short={short_m:>3}m burn={b_short:6.2f} "
f"threshold={thr:>4} -> {'FIRE' if fire else 'quiet'}")
evaluate("at the end of the 60-minute incident", INCIDENT[1])
evaluate("5 minutes after the incident ended (long windows still hot, short windows clean)", INCIDENT[1] + 5)
evaluate("one hour after (now)", NOW)runs: 12898
task success rate : 96.030%
cost per SUCCESSFUL task: $0.0473 (all spend / successful runs)
cost per run : $0.0454
p95 run latency : 9.34 s
escalation rate : 6.50%
at the end of the 60-minute incident
PAGE long= 60m burn= 16.53 short= 5m burn= 14.67 threshold=14.4 -> FIRE
PAGE long= 360m burn= 3.35 short= 30m burn= 16.74 threshold= 6.0 -> quiet
TICKET long=4320m burn= 0.80 short=360m burn= 3.35 threshold= 1.0 -> quiet
5 minutes after the incident ended (long windows still hot, short windows clean)
PAGE long= 60m burn= 15.24 short= 5m burn= 0.00 threshold=14.4 -> quiet
PAGE long= 360m burn= 3.36 short= 30m burn= 14.48 threshold= 6.0 -> quiet
TICKET long=4320m burn= 0.80 short=360m burn= 3.36 threshold= 1.0 -> quiet
one hour after (now)
PAGE long= 60m burn= 0.45 short= 5m burn= 1.54 threshold=14.4 -> quiet
PAGE long= 360m burn= 3.32 short= 30m burn= 0.68 threshold= 6.0 -> quiet
TICKET long=4320m burn= 0.79 short=360m burn= 3.32 threshold= 1.0 -> quietReading the SLIs. Over three days, cost per successful task is $0.0473 against $0.0454 per run (the gap is the money spent on failed runs). A 60-minute incident barely moves the three-day task success rate (96.0%, with a 3% baseline failure rate). A long window hides a short outage. That is why alerts use burn rates over short windows, not the SLO's own window.
4.3 Burn rates, in words#
11A.2, 4.5 defines the error budget and the burn rate (observed bad ratio divided by the allowed ratio) and lists the three rules from the Google SRE Workbook, which the script above uses: page at 14.4x over 1 hour and 5 minutes, page at 6x over 6 hours and 30 minutes, ticket at 1x over 3 days and 6 hours. Here the SLO is 95% task success over 30 days, so the budget is the 5% of runs allowed to fail. Each rule needs a high burn over both windows: the long one says the problem is sustained, the short one says it is still happening.
Read the three evaluations:
- At the end of the incident the one-hour burn is 16.5x and the five-minute burn is 14.7x: both over 14.4, so the page fires. The slower rules stay quiet, because the 6-hour and 3-day windows dilute the hour.
- Five minutes after the incident ended, the one-hour window still shows 15.2x (it still contains 55 bad minutes), but the five-minute window is clean at 0. The page stops immediately. This is the job of the short window: it makes the alert resolve as soon as the problem does, instead of paging for another hour.
- An hour later, nothing fires. The six-hour burn is still 3.3x, but the six-hour window is only a short window for the ticket rule, whose three-day long window is at 0.79x, below the 1x threshold. Had the incident lasted longer, the ticket rule would be the one to notice a sustained slow burn.
4.4 Dashboard panels for agents#
A dashboard should answer, in this order: is it working, is it fast enough, is it affordable, why not?
| Row | Panels |
|---|---|
| Is it working? | Task success rate; escalation rate; error-class stack (by Part 2's classes) |
| Is it fast? | Run latency p50, p95, p99 by feature; TTFT p95; step count p95 |
| Is it affordable? | Cost per successful task; tokens per run; retry amplification |
| Why not? | Tool error rate by tool; loop-stop and budget-stop counts; provider error rate by provider and model |
| What changed? | Annotations for deploys, prompt versions and model changes (11A.2, 5.3); gen_ai.prompt.version as a filter |
These are the panels of 11A.2's dashboard set (5.1), regrouped by question, with the queries for the agent panels in 4.8. Two additions for agents: group by agent or feature, not only globally, and show the sample size next to every percentile (Part 1).
4.5 Alert design for agents#
The general rules are in 11A.2, 6.1 (actionable, symptom-based, routed by severity), 4.6 (page or ticket), 6.3 (alert when signals stop arriving) and 6.6 (runbooks and fatigue). For agents, apply them like this:
- Page on symptoms users feel: task-success burn, run-latency burn, a sustained rise in give-ups. Do not page on a single provider error or a high token count.
- Ticket on trends: slow burn, rising cost per successful task, rising step counts.
- Treat a guardrail firing at scale as a regression signal: a jump in
loop_stoporbudget_stop(Part 2) is not noise. - Give cost its own alerts: a runaway agent is an incident. Budget and kill-switch design is in 11B.7.
A first set of illustrative SLOs for a support agent (choose yours from product needs and the cost of errors, not by copying):
| SLO | Target | Window |
|---|---|---|
| Task success | 95% of runs | 30 days |
| Run latency | 95% of interactive runs finish within 20 s | 30 days |
| Cost per successful task | p95 under your budgeted figure | 7 days |
| Escalation rate | under 10% | 30 days |
Part 5: Evaluate it#
Concept lessons
- 10A.7 — Evaluating agents: task success, cost per successful task, steps and latency distributions are the metrics this lesson monitors in production.
- 10A.9 — Offline and online evaluation: the outcome signal for the task-success SLI (sampled judges, human review, assertion monitors) and anomaly detection.
- 10A.2 — Building eval datasets: the failure classes from Part 2 are useful tags for cases (11A.4).
- 10A.12 — Evaluating multi-agent systems for long and multi-agent runs, where run-latency tails are widest.
What to measure for this lesson's topic. Not the agent's answer quality, but whether your monitoring is right: (1) are percentiles computed correctly? (2) does the error classifier agree with a human? (3) does the alert fire when it should and stay quiet when it should not? (4) does replay reproduce a recorded decision?
A tiny eval design for the monitoring itself.
- Inputs: a synthetic day of runs with a known injected incident (as in Part 4) and a labelled set of 50 error records with a human-assigned class.
- Metrics: (a) classifier accuracy against the human labels; (b) alert detection delay (minutes from incident start to page) and false-page count over a clean week; (c) replay equality (replayed decisions equal recorded decisions for 100% of stored sessions).
- Pass rules: classifier accuracy at least 95% with
otherunder 5%; the page fires within 15 minutes of an incident that burns at 14.4x or more; zero false pages in the clean week; 100% replay equality on unchanged code.
The DeepEval lessons (required track)
- 10B.5 — DeepEval tracing and agent evaluation: step efficiency, task completion and loop detection metrics on traced runs. 10B.4 — Built-in metrics lists the rest.
The Inspect AI lessons (optional)
- (optional) 10B.15 — Sandboxes, limits and approval: limits and approval as part of an eval's design, the eval-time counterpart of budget stops and audit records.
- (optional) 10B.13 — Logs and analysis for latency and cost analysis from logs, and 10B.16 — Evaluating agents with Inspect.
Common misconceptions#
- "Average latency is the number to watch." Averages hide the slow runs users complain about. Watch p50, p95 and p99 of run latency.
- "Run latency is step latency times the number of steps." The number of steps varies, and each step has its own tail. In the example, the naive product underestimated the true p95 (11.3 s versus 13.6 s).
- "I can average p95s across hosts." Percentiles do not combine by averaging. Combine raw data or histograms.
- "A hash chain means nobody can tamper with the log." It makes edits detectable, not impossible, and it cannot see tail truncation without an anchored head hash.
- "The audit log is the trace with a longer retention." They have different content, integrity and access rules. The audit log is minimal and tamper-evident.
- "Retries are free." Retries add latency, cost and load. During an outage they can multiply the problem.
- "Replay shows what the model would do now." Replay serves recorded answers. It tests your code against the past; only a live re-run tests the model.
Key takeaways#
- Measure run latency as percentiles, next to step count and cost. Separate model time, tool time and waiting.
- Compute percentiles from raw data or histograms, never by averaging percentiles. With few observations, a percentile is noise: show the sample size.
- Classify failures into a small, stable taxonomy: provider limits and errors, timeouts, tool errors, validation, refusals, budget stops, loop stops.
- Watch retry amplification, retry rate and give-up rate over short windows. A day-long average hides an outage.
- An audit log is minimal, tamper-evident (a hash chain) and anchored outside the file. It records actions and decisions, not conversations.
- Session replay records the model's and tools' outputs at the boundary, so a session can be re-run without side effects. Treat replay files as sensitive.
- Agent SLIs: task success, cost per successful task, p95 run latency, escalation rate. Alert on multi-window burn rates, and make sure "success" is actually measured.
Terms introduced in this lesson#
| Term | Meaning |
|---|---|
| Percentile (p50, p95, p99) | The value that a given share of observations fall below |
| Nearest-rank percentile | A percentile that returns an observed value at rank ceil(p/100 x n) |
| Interpolated percentile | A percentile computed between the two nearest observations |
| Step latency / run latency | Time for one model or tool call versus time for a whole agent run |
| Error taxonomy | A small, stable list of failure classes used to count and alert |
| Give-up rate | Share of calls that exhausted their retries |
| Audit log | A minimal, tamper-evident record of actions and decisions |
| Audit hash chain | Audit records that each include the hash of the previous one, so edits are detectable |
| Anchor (head hash) | A copy of the latest chain hash stored where the writer cannot change it |
| Session replay | Re-running a recorded session using recorded model and tool outputs |
| Escalation rate | The share of runs handed to a human |
Exercises#
- Run latency from spans. Using the mini tracer from 11A.1, 3.9, produce 200 simulated runs and compute run p50, p95 and p99 from the
invoke_agentspan durations. Then compute the share of run time spent inchat, inexecute_tool, and elsewhere. Hint: group child spans bygen_ai.operation.name; time not covered by any child is "other". - Wrong percentiles. Reproduce the "mean of two p95s" mistake with your own two groups, then fix it by merging histograms with fixed bucket edges. How close is the histogram estimate to the exact answer? Hint: bucket counts add; estimate the percentile by finding the bucket where the cumulative count crosses 95%.
- Extend the taxonomy. Add
quota_exhausted(a 429 that must not be retried) and makeclassifyaccept the provider's error body. Use 03.8, 4.2 to decide what to look for. Hint: look at the error code or type in the body, not only the status. - Catch the anchor gap. Delete the last two records of the audit file and show that
verifystill says "intact". Then add ananchorfile holding the head hash and averify_with_anchorfunction that catches the truncation. Hint: after verification, compare the final record's hash to the anchored head; a shorter chain will not match. - Replay as a test. Record two sessions, change the agent's prompt text so the scripted model is the same but the agent sends an extra message, and make replay fail with a useful message. Hint: also record
n_messagesand assert it inReplayer.call_model. - A burn-rate alert for cost. Define an SLI "cost per successful task under $0.08" per hour. Evaluate multi-window burn for it using the script's runs. Hint: a run is "bad" if its hour's cost per success exceeds the threshold; compute per-hour first, then burn.
Check yourself#
- Why is run latency not step latency times a constant?The number of steps varies from run to run, and each step has its own distribution, so long runs form a tail that no single step latency predicts.
- What is the p95, and why does the mean hide the problem it describes?The p95 is the value that 95% of observations are below; the slowest 5% exceed it. The mean is pulled by the whole distribution and says nothing about the tail users complain about.
- What is the difference between nearest-rank and interpolated percentiles, and when do they differ most?Nearest-rank returns an observed value at rank
ceil(p/100 x n); interpolation computes a value between neighbours. They differ most with few observations and a heavy tail, as in the ten-point example (p95 of 9.80 s versus 6.11 s). - Why can you not average the p95 values from two hosts?Percentiles ignore how many observations each host had. Averaging gives equal weight to a busy and a quiet host. Combine raw data or histogram buckets instead.
- Name six classes in the agent error taxonomy.For example
provider_rate_limit,provider_server,timeout,tool_error,validation,refusal,budget_stop,loop_stop. - What is retry amplification, and why did the one-day average hide the incident?Attempts divided by logical calls. A 40-minute incident was diluted by 23 hours of normal traffic, so the day average was 1.05x while the incident ran at 2.01x.
- What goes in an audit record for a tool call, and what is deliberately left out?Actor, action, target, decision, a hash of the arguments, small details, links to the trace, and the chain hashes. The raw arguments and conversation text are left out, so the log does not become a second copy of sensitive data.
- What does a hash chain detect, and what can it not detect on its own?It detects edits to or removal of earlier records. It cannot detect truncation of the tail, or a fully rewritten chain, unless the head hash is anchored somewhere the writer cannot edit.
- What must you record to replay a session without a model or side effects?Every model response and tool call and result at the boundary, plus the versions and parameters, and any clock or ids your code uses.
- Why is cost per successful task more informative than cost per run?Cost per run averages spending over successes and failures alike. Cost per successful task includes the money wasted on failed runs, so regressions in success rate show up as higher unit cost.
Further resources#
- 11A.2 — Metrics, Dashboards, SLOs and Alerting: histograms, Prometheus and Grafana, the SLO document, the alert rules and 4.8 agent metrics.
- 03.8 — Errors and Retries: provider error taxonomies, retryability and backoff.
- 11A.1 — Tracing and Observability: the spans these numbers come from (3.7 to 3.13), the tools (Part 5) and the debugging playbook.
- 08A.14 — Reliable and Safe Agents: per-step logging and trajectory replay.
- 12.6 — Securing Tools, Agents and MCP: the audit record for tool calls and forensics.
- 11B.7 — Rate Limits, Kill Switches and Alerts: spend alerts and kill switches.
- 08A.12 — Human-in-the-Loop and Approval Gates: the approvals your audit log records.
- Google SRE Workbook — Alerting on SLOs: the multi-window, multi-burn-rate method.
- OpenTelemetry GenAI metrics conventions:
gen_ai.invoke_agent.durationand related names (see also 11A.1, 3.13).
← 11A.2 — Metrics, Dashboards, SLOs and Alerting | Next: 11A.4 — Production Traces into Eval Datasets
← 11A.2 — Metrics, Dashboards, SLOs and Alerting | Module 11A overview | 11A.4 — Production Traces into Eval Datasets →