Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live
An agent misbehaves and the log is all you have. Five short traces, five signatures, and a small reader that names the missing pattern (loop bound, loop test, isolation, memory or context management) and the fix that treats the cause.
What you will learn
- Spot five trace signatures: a repeated call, a leak, a forgotten fact, a growing context and a tool_use that never ran
- Name the missing pattern behind each: loop bound, loop test, subagent isolation, memory, context management
- Write small Python checks that diagnose a trace
- Choose a memory scope (turn, session or persistent) by how long a fact must live
Before you start
- The agentic loop and stop_reason
- Memory and context-window patterns for Claude agents
A stock checker asks about item K-204 and gets "0 in stock". Then it asks again, and again: four times, the same call and the same answer. Then the harness kills it, because the call budget is spent. Which pattern is missing? The log doesn't say. You read it, and you name it.
This article teaches one skill: read an agent's trace, find its signature, and name the missing design pattern. The five traces are test data from our own agents, and the reader is plain Python with no model call.
One sign, one missing pattern
Think of a dashboard light. It doesn't tell you the engine is broken; it points at the part that's missing. A trace works the same way: it shows a symptom, and the missing pattern is the cause.
traces.py: five agents, five logs
Each step is a tuple: a call number, a kind and some text.
"""Five trace excerpts from our test agents. A step is (call, kind, text)."""
# Agent 1: stock_checker asks the same question again and again
LOOP = [
(1, "tool_use", "check_stock K-204"), (1, "result", "0 in stock"),
(2, "tool_use", "check_stock K-204"), (2, "result", "0 in stock"),
(3, "tool_use", "check_stock K-204"), (3, "result", "0 in stock"),
(4, "tool_use", "check_stock K-204"), (4, "result", "0 in stock"),
(5, "end", "killed by the harness: call budget spent"),
]
# Agent 2: reply_reviewer is a subagent, briefed on ticket T-9 only
LEAK = [
(1, "brief", "review the draft reply for T-9"),
(1, "context", "inherited 14 messages from the parent"),
(1, "text", "Draft is fine. Also apologise for the T-8 delay."),
]
# Agent 3: delivery_planner, two sessions
FORGOT = [
(1, "user", "fact: address = Dock 4"),
(2, "text", "Noted. Delivery goes to Dock 4."),
(3, "end", "session ended"),
(1, "text", "Which address should I use?"),
]
# Agent 4: log_digger reads one big log page per call
OVERFLOW = [
(1, "context", "1200"), (2, "context", "5800"),
(3, "context", "10400"), (4, "context", "15000"),
(5, "context", "19600"), (6, "context", "24200"),
(6, "end", "stopped: context over the budget"),
]
# Agent 5: migration_checker has a plan of four steps
PREMATURE = [
(1, "text", "Step 1 of 4: checking the tables."),
(1, "tool_use", "list_tables"),
(1, "stop", "tool_use"),
(1, "end", "harness returned after the text block"),
]
reader.py: one check per signature
"""Read a trace, find its signature, name the missing pattern."""
import re
LIMIT = 20000 # our own context budget for the test agents
def kinds(steps, kind):
return [text for _, k, text in steps if k == kind]
def loops(steps):
uses = kinds(steps, "tool_use")
top = max(uses, key=uses.count, default="")
if uses.count(top) >= 3:
return f"{top} repeated {uses.count(top)} times"
def stops_early(steps):
answered = {call for call, k, _ in steps if k == "result"}
for call, kind, text in steps:
if kind == "tool_use" and call not in answered:
return f"{text} was asked for and never run"
def ids(steps, kind):
return set(re.findall(r"T-\d+", " ".join(kinds(steps, kind))))
def leaks(steps):
extra = ids(steps, "text") - ids(steps, "brief")
if extra:
return f"{' '.join(sorted(extra))} is not in its brief"
def forgets(steps):
facts, ended = {}, False
for _, kind, text in steps:
if kind == "user" and text.startswith("fact: "):
key, value = text[6:].split(" = ")
facts[key] = value
elif text == "session ended":
ended = True
elif ended and kind == "text":
for key, value in facts.items():
if f"Which {key}" in text:
return (f"asks for the {key} again, "
f"it was {value}")
def overflows(steps):
sizes = [int(text) for text in kinds(steps, "context")]
rising = all(a < b for a, b in zip(sizes, sizes[1:]))
if len(sizes) > 2 and rising and sizes[-1] > LIMIT:
return (f"context {sizes[0]} -> {sizes[-1]} chars, "
"never cleared")
CHECKS = [
(loops, "loop bound", "cap the turns, stop when nothing changes"),
(stops_early, "loop test", "go on while stop_reason is tool_use"),
(leaks, "subagent isolation", "hand it only its brief"),
(forgets, "memory", "save facts to notes, view them first"),
(overflows, "context management", "clear old results or compact"),
]
def diagnose(steps):
for check, missing, fix in CHECKS:
found = check(steps)
if found:
return found, missing, fix
return "no signature found", "none", "read more of the trace"
loopsfinds the call made most often; three or more of the same call is a loop.stops_earlycollects every call that got a result. Atool_usewithout one never ran.leakscompares the ticket ids in the subagent's output with the ids in its brief. An extra id is a leak.forgetskeeps each stated fact, marks where the session ended, and flags a question about a known fact after the reset.overflowswants a size that only rises and ends above the budget. The 20,000 character budget is our own example number, not a platform limit.
Five traces, five names
trace 1 stock_checker: check_stock K-204 repeated 4 times
missing: loop bound -> cap the turns, stop when nothing changes
trace 2 reply_reviewer: T-8 is not in its brief
missing: subagent isolation -> hand it only its brief
trace 3 delivery_planner: asks for the address again, it was Dock 4
missing: memory -> save facts to notes, view them first
trace 4 log_digger: context 1200 -> 24200 chars, never cleared
missing: context management -> clear old results or compact
trace 5 migration_checker: list_tables was asked for and never run
missing: loop test -> go on while stop_reason is tool_use
Traces 1 and 5 are both loop problems, with two different holes. The stock checker has no bound. The migration checker stopped on the wrong test: the stop reason was tool_use, but the harness returned after the text block. The right test is covered in the agentic loop and stop_reason.
Treat the cause, not the symptom
Each trace has a tempting fix that hides the symptom. The pattern removes the cause.
| Trace | Tempting fix | The pattern |
|---|---|---|
| It loops | Tell it to try harder | Cap the turns, stop when nothing changes |
| The subagent leaks | Tell it to ignore the rest | Hand it only its brief (see context isolation with subagents) |
| It forgot | A bigger window | Save facts to notes and view them first (see memory patterns) |
| The window overflows | A shorter question | Clear old results, or compact (both in beta) |
| It stopped early | A longer prompt | Go on while the stop reason is tool_use |
A bigger window still resets. A shorter question doesn't shrink old results. Telling a subagent to ignore something doesn't hide it.
How long must the fact live?
The memory fix raises a design question: how long should an agent keep a fact? scopes.py answers it with two yes-or-no questions: is the fact needed after the reply, and is it needed after a window reset?
"""Memory scope: how long must an agent's facts live?"""
AGENTS = [
# name, needs it after reply, needs it after reset
("invoice_formatter", False, False),
("support_chat", True, False),
("onboarding_guide", True, True),
]
WHERE = {"turn": "this request only",
"session": "the chat's messages list",
"persistent": "the memory tool"}
def scope(after_reply, after_reset):
if not after_reply:
return "turn"
if not after_reset:
return "session"
return "persistent"
memory scope
invoice_formatter turn this request only
support_chat session the chat's messages list
onboarding_guide persistent the memory tool
- The invoice formatter handles one invoice per request. Nothing is needed after the reply: a turn.
- The support chat remembers the order during one chat, but not after a reset: a session, held in the messages list.
- The onboarding guide remembers preferences for next week. That must survive a reset: persistent, in the memory tool.
Pick the shortest scope that still works, and keep nothing longer than the agent needs.
Quick recap
- Read the signature: what repeats, what leaks, what never ran, what grows.
- Name the missing pattern: loop bound, loop test, subagent isolation, memory or context management.
- Pick the fix that adds that pattern, not a patch on the symptom.
Try it yourself
Write a sixth trace where a subagent calls the same tool four times and mentions a ticket outside its brief. Run diagnose on it. It reports only the first match in CHECKS; change it to report every signature it finds, and decide which fix you'd apply first.
Related course on Udemy
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.