Sub topic 16
Tracing and reviewing multi-agent runs
This chapter assumes you have read the earlier chapters on the orchestrator-worker pattern, delegation briefs, and result aggregation. You should also be able to read basic Python and JSON. A multi-agent run is hard to debug after the fact, so this chapter shows how to record what happened and how to review it.
Why a multi-agent run needs a trace
With a single agent, you can scroll back through one conversation and see every step. With subagents, that is no longer true. Each subagent works in its own context, and the orchestrator only sees the summary it gets back. When the final result is wrong, the transcript you have may not show why.
Some typical questions you cannot answer without a record:
- Which subagent changed
src/cli.py, and what brief did it receive? - Did a subagent really run the tests it claims to have run?
- Which task took 4 minutes while the others took 20 seconds?
- Did a failed task get retried, and what happened on the retry?
- Why did the run cost three times what you expected?
A trace is a structured log of the run. It records who did what, in what order, with what inputs and outcome. You write it as the run happens, not afterward.
What to record
Record events at two levels. A span is one unit of work with a start and an end, such as "the orchestrator ran" or "subagent add-tests ran". An event is a single thing that happened inside a span, such as a tool call.
| Field | Where | Why you need it |
|---|---|---|
| `run_id` | every record | Separates one run from another in the same log file |
| `span_id` and `parent_id` | spans | Rebuilds who started whom |
| `name` | spans | Names the task, for example `update-docs` |
| `brief` | span start | Shows exactly what the subagent was told |
| `tool_call` events | inside a span | Shows what the subagent actually did |
| `status` and `error` | span end | Separates ok, failed, and timed out |
| `duration_s` | span end | Finds slow tasks |
| `summary` | result event | Shows what the subagent reported back |
| token counts | span end | Ties a task to its cost, if your runtime exposes them |
| branch or worktree | span start | Links the work to a diff you can inspect |
The brief matters most. When a subagent does the wrong thing, the first check is whether the brief was wrong or the subagent ignored it. You can only make that check if the brief was saved.
The shape of a trace
The trace forms a tree. The orchestrator is the root. Each subagent is a child span. Tool calls and results are events attached to a subagent span. If a task is retried, the retry is a new sibling span, so both attempts stay visible.
A minimal tracer in Python
The script below writes a trace as JSON Lines, which is one JSON object per line. This format is easy to append to, even when several tasks write at nearly the same time, and easy to read with grep, jq, or a script. The script runs two placeholder subagents concurrently, makes one of them fail, and then prints a report built from the file.
import asyncio
import json
import time
import uuid
from contextlib import contextmanager
from pathlib import Path
class Tracer:
def __init__(self, path: str):
self.path = Path(path)
self.run_id = uuid.uuid4().hex[:8]
def emit(self, **fields) -> None:
record = {"run_id": self.run_id, "ts": time.time(), **fields}
with self.path.open("a", encoding="utf-8") as f:
f.write(json.dumps(record) + "\n")
@contextmanager
def span(self, name: str, parent: str | None = None, **attrs):
span_id = uuid.uuid4().hex[:8]
start = time.monotonic()
self.emit(event="start", span_id=span_id, parent_id=parent, name=name, **attrs)
status, error = "ok", None
try:
yield span_id
except Exception as exc:
status, error = "failed", f"{type(exc).__name__}: {exc}"
raise
finally:
self.emit(
event="end",
span_id=span_id,
name=name,
status=status,
error=error,
duration_s=round(time.monotonic() - start, 3),
)
async def run_subagent(tracer: Tracer, parent: str, name: str, brief: str, fail: bool = False) -> dict:
with tracer.span(name, parent=parent, brief=brief) as span_id:
tracer.emit(event="tool_call", span_id=span_id, tool="read_file", target="src/cli.py")
await asyncio.sleep(0.1) # Placeholder for real agent work.
if fail:
raise TimeoutError("no result after 0.1s")
summary = f"finished {name}"
tracer.emit(event="result", span_id=span_id, summary=summary)
return {"name": name, "status": "ok", "summary": summary}
async def main(tracer: Tracer) -> None:
with tracer.span("orchestrator") as root:
await asyncio.gather(
run_subagent(tracer, root, "update-docs", "Update the README usage section."),
run_subagent(tracer, root, "add-tests", "Add tests for parse_args.", fail=True),
return_exceptions=True,
)
def report(path: str) -> None:
spans: dict[str, dict] = {}
for line in Path(path).read_text(encoding="utf-8").splitlines():
rec = json.loads(line)
sid = rec.get("span_id")
if rec["event"] == "start":
spans[sid] = {"name": rec["name"], "tools": 0, "status": "running", "duration": None, "error": None}
elif rec["event"] == "tool_call":
spans[sid]["tools"] += 1
elif rec["event"] == "end":
spans[sid].update(status=rec["status"], duration=rec["duration_s"], error=rec["error"])
for s in spans.values():
print(f"{s['name']:<14} {s['status']:<8} tools={s['tools']} duration={s['duration']} error={s['error']}")
if __name__ == "__main__":
log_path = "trace.jsonl"
Path(log_path).unlink(missing_ok=True)
tracer = Tracer(log_path)
asyncio.run(main(tracer))
report(log_path)Three details are worth noting.
- The
finallyblock writes theendrecord even when the task raises, so a failed task still leaves a complete span. - A span with a
startrecord but noendrecord shows asrunningin the report. After a crash, that tells you which task was in flight. - The tracer stores the brief on the span. This is what lets you compare the instruction with the outcome later.
In a real system, run_subagent would call your agent runtime, and the runtime would feed tool calls into tracer.emit. If your runtime already produces its own logs or traces, record the span_id of each subagent in your orchestrator log. That lets you join the two sources later.
Reviewing a run
Review has two purposes. The first is debugging a bad outcome. The second is improving the next run. Work in this order.
- Read the report first. Look for failed spans, spans still
running, unusually long durations, and tasks with zero tool calls. A subagent that reports success without any tool calls may not have done any work. - Open the brief of any suspicious task. Check whether it stated the goal, scope, and finish condition. Most bad outcomes trace back to a vague brief, not to a bad subagent.
- Compare the summary with the evidence. If a summary says "tests pass", find the tool call that ran the tests and its output. This is the same verification step from the earlier chapter, now done against a record instead of memory.
- Check scope. Compare the files each subagent changed against the scope in its brief. In a worktree setup,
git diff --staton each branch gives this directly. - Look at the overlaps. If two subagents touched the same file, the decomposition was probably wrong, or the tasks should have run in sequence.
Common errors
- Logging only the orchestrator. You then see the summaries but not the briefs or tool calls, which is the same blind spot you started with.
- Logging the summary but not the brief. You can see what came back but not what was asked.
- Using timestamps alone to order events. Concurrent tasks interleave, so use
span_idandparent_idto group events and use timestamps only within a span. - Keeping one log file per process without a
run_id. Runs mix together and you cannot tell them apart. - Forgetting retries. If a retry reuses the same span name without a new
span_id, you cannot tell the first attempt from the second. - Reading the trace only when something breaks. Skim a few successful runs as well. They show you your normal duration, tool count, and cost, which you need as a baseline to spot anything abnormal.
Exercise
A subagent's summary says "added tests, all passing", but your report shows its span had tools=0. What does this suggest, and what do you check next?
Show answer
A subagent that made no tool calls cannot have written files or run pytest, so the summary is probably unsupported or invented. Open the span's brief to see whether it was clear, check the branch or worktree with git diff to see whether any files changed, and rerun the test command yourself before accepting the result. If the trace is missing tool calls because the runtime did not report them, fix the logging first, since you cannot verify any task without that evidence.
Exercise
Your orchestrator retries a failed task by running it again. What must be true of the trace so you can tell the two attempts apart?
Show answer
Each attempt must be its own span with a new spanid, both with the same parentid (the orchestrator) and ideally the same name plus an attempt number attribute. The first span ends with status failed and its error. The second span ends with its own status. If the retry reused the first span, the failure and its error would be lost.