Cruxly › AI engineering › Agentic Systems
Debugging an Agent: Reading a Trace
find the first wrong span, not the last; replay the run; turn the bug into a test
Open the interactive lessonPrompt: "Our support agent just ran 38 steps on a single refund ticket and then gave up. The customer is angry. You have access to the logs. Walk me through what you do, in order."
25 minutes first. The weak answer is "I would read the transcript and tweak the prompt". The strong answer names what the trace must contain, how you localise the first wrong decision, how to tell three common root causes apart, and how the fix gets locked in so that it does not come back.
What a useful trace contains
A transcript shows what was said. A trace shows what happened. When an agent loops, the transcript is a wall of near-identical messages, and the cause is usually outside the text: a raw tool response that was different from what the model saw, a retry hidden inside a wrapper, a context that had quietly lost an important fact. For each step, record a span.
| Span type | Fields worth storing |
|---|---|
| Model call | model name and version, full input messages (or a hash plus a pointer to the stored copy), output, stop reason, input and output tokens, latency, temperature and other parameters |
| Tool call | tool name, the exact arguments the model produced, the raw result from the tool, the result as passed back to the model, status code or exception, latency |
| Every span | span id, parent span id, run id, start time, step number, tool schema version, prompt version |
Two of those are easy to omit and expensive to lack. Raw result versus what the model saw is how you find a swallowed error: if they differ, something between the tool and the model changed the meaning. Parent span id is what makes a multi-agent or nested run readable as a tree, so you can see that a sub-agent's 20 calls belonged to one delegated step.
Store enough to replay, and be deliberate about what is sensitive. Tool results often contain customer data. Redact or tokenise fields at write time where you can, set a retention period, and restrict who can open traces; a trace store is a copy of your production data in a new place.
A worked trace: the agent that loops, and finding the first wrong span
Here is a trace, for example, of a refund ticket that looped. Tokens and times are illustrative.
| # | Span | Arguments | Raw result | What the model saw | Tokens in / out | ms |
|---|---|---|---|---|---|---|
| 1 | model | system + ticket | decides to look up the order | same | 1,800 / 60 | 900 |
| 2 | tool get_order | ORD-8812 | {status: delivered, total: 1499} | same | 140 | |
| 3 | model | + order | decides to refund | same | 2,100 / 70 | 950 |
| 4 | tool refund | ORD-8812, 1499 | HTTP 503 from payments | "" (empty string) | 3,000 | |
| 5 | model | + empty result | "no output, try again" | same | 2,250 / 40 | 800 |
| 6 | tool refund | ORD-8812, 1499 | HTTP 503 | "" | 3,000 | |
| 7 to 36 | model, tool refund repeated | identical | HTTP 503 | "" | 2,300 to 4,900 in each | |
| 37 | model | context full of failures | "I cannot complete this" | same | 4,900 / 55 | 900 |
The last span is where the user saw the failure, and it is the wrong place to look. The model's final message is a reasonable reaction to a context that was full of empty results. Work backwards to the first span where the model's belief and the world disagreed. That is span 4: payments returned a 503, and the model was told nothing. Now ask why, in three steps.
@@ 1 | Compare the raw result with what the model saw Span 4 raw: 503. Model saw: empty. So a wrapper converted the error into an empty string. This is a swallowed tool error.
@@ 2 | Rule out the other two causes from the same trace Were the arguments correct? Yes: right order id, amount matches the order total, so the tool description did not mislead the model. Was the needed information in context? Yes: span 3 input shows the order, so nothing was missing. Both alternatives are excluded by data, not by a guess.
@@ 3 | Fix the cause, then the amplifier Cause: the wrapper must return an actionable error, such as "payments service unavailable (503); the refund was not issued; do not retry more than twice, then tell the user it is pending". Amplifier: nothing stopped the identical call 30 times, so add a cap on repeated identical calls and a step budget.
The same shape of loop can have two other root causes, and each leaves a different fingerprint.
| Root cause | What the trace shows | Typical fix |
|---|---|---|
| Tool description misleads | Arguments are wrong in a consistent way, for example amount sent in paise when the tool wants rupees, and the tool returns a clear error each time | Rewrite the description and parameter names, add units, tighten the schema |
| Missing context | The model's input at the failing span does not contain a fact it needed, so it guesses (invents an order id) | Put the fact in context, or give a tool that fetches it; check whether truncation dropped it |
| Swallowed or vague tool error | Raw result is an error; the model saw empty or generic text; the model retries or invents an explanation | Return structured, actionable errors; never turn an exception into success |
:::key Read from the first divergence, not from the end A long run is mostly consequences. The first span where the model's picture of the world differs from the world is usually the cause, and everything after it is the agent reasonably reacting to bad information. :::
Replaying a failed run, and turning the fix into a regression test
A bug you cannot reproduce is a bug you cannot fix with confidence. Agents are stochastic, so rerunning the live agent on the same ticket may simply succeed, and you will not know whether the fix worked or the dice did. Replay removes the randomness by playing back what was recorded.
- Tool replay. Stub every tool so it returns the recorded raw result for the same call (matched by tool name and arguments). The environment is now identical to the failing run: payments returns 503 exactly as it did.
- Model replay. Feed the recorded model outputs step by step to reproduce the exact path up to the span you care about. That is how you inspect the state at span 4 without waiting for the live model to wander there again.
- What-if from a span. Replay the recorded history up to a chosen span, then let the live model take over from there with your fix in place (the new tool description, the new error text). If it now stops after two attempts and reports the failure, the fix works for that situation.
Setting temperature to 0 is not replay. It narrows the variation but does not guarantee identical outputs across model versions or infrastructure, so recorded outputs are the dependable way.
Then turn every fixed bug into a regression case. The trace you just debugged contains almost everything an eval case needs.
case: refund-payments-503
initial: fixture orders_v3, ORD-8812 delivered, total 1499
tool_stubs: refund -> HTTP 503 every time
user: "refund my order ORD-8812"
assert: refund called at most 2 times
assert: final reply says the refund is NOT yet issued and gives a next step
assert: no refund row exists; total steps <= 10
Notice the assertions describe the behaviour you want under that fault, not the exact words. A test that fails whenever the model phrases a sentence differently is a test people turn off. Put the case into the golden set from the previous lesson, so it runs with every prompt or model change.
Close the loop on the amplifiers too. Each bug usually has a cause and a reason it was expensive. Fix the cause (the swallowed error), then cap the cost (repeated-call detector, step and token budgets) and make sure those caps are tripping alarms rather than failing silently.
Follow-ups they will ask
"We have logs already. Why is that not enough?" Logs are usually text lines written for humans, with no parent ids, no raw versus seen results, and no way to replay. You can build traces on top of structured logs, or use an observability tool that speaks the tracing model (spans with parents); what matters is the fields, not the vendor.
"The agent loops sometimes but the trace looks fine. What next?" Look at the model-call spans, not the tool spans. Check what the model saw as input at the first looping step: a truncated history, an instruction that conflicts with another, a tool result so long that the question fell out of attention. Also compare against a passing run of the same task, span by span, and find where they split.
"How do you debug a bug that happens once in 200 runs?" Make runs cheap to find: tag traces with outcome and trajectory flags from the graders, and query for the odd ones (repeated identical calls, runs over budget). Then replay the rare one, instead of trying to catch it live.
"Is a bigger or newer model the fix?" Sometimes, but only after the trace says the model made a bad decision from correct information. If the information was wrong, missing, or hidden, a stronger model will make the same mistake more convincingly.
"What do you alert on?" Not on every error. For example: runs exceeding the step budget, repeated identical calls, tool error rate per tool, a jump in tokens per successful task, and gate trips. These are cheap to compute from spans and each points at a specific class of bug.
How to say it in the interview
"First I need a trace, not a transcript: every model call and tool call as a span, with arguments, the raw result, tokens, latency and a parent id, so I can see the tree. Then I look for the first span where reality departed from what the agent assumed, not the last span where it gave up. The usual causes are a tool description that misleads the model, context the model never had, or a tool error that something swallowed on the way back. The trace tells them apart. Then I replay the run from recorded model and tool outputs so I can reproduce it, fix the cause, and save the replay as a regression test."
Checklist
- Recorded every model and tool call as a span with arguments, raw result, tokens, latency and parent id
- Stored the raw tool result next to what the model actually received
- Diagnosed from the first span where belief and world disagreed, not from the last message
- Told apart misleading tool description, missing context and swallowed tool error from the trace
- Replayed the run from recorded tool results and model outputs, not by rerunning and hoping
- Turned each fixed bug into a regression case asserting behaviour, not exact wording
- Fixed the cause and capped the amplifier: repeated-call detector, step and token budgets
- Redacted sensitive fields, set retention and limited access on the trace store
Related lessons
- The Agent Loop in Depth: ReAct, Plan-and-Execute, Reflection and Stop Conditions
- Designing Tools an Agent Can Actually Use
- Agent Memory: Working, Episodic, Semantic and Procedural, Without the Rot
- Context Engineering for Long-Horizon Agents
- Frameworks, Protocols and Durable Execution: MCP, A2A and Long-Running Agents
- Reliable Agents: Retries, Idempotency, Checkpoints and Sagas