Scaling AI Agents: Latency Attribution and Failure Diagnosis
As AI agents move from single-developer experiments to production workloads, debugging shifts from replaying individual conversations to analyzing aggregated metrics across sessions, machines, and time. This article explains why local session views fall short at scale, how to design a structured observability layer aligned with the agent execution model (session, turn, step, span), and exactly which data fields to collect. It covers practical techniques for attributing latency to model inference vs. tool execution, breaking down token costs by model, step count, and tool output size, and classifying and tracing failures from tool errors to process crashes. It also provides concrete implementation guidance—including an example data structure, storage tiering, redaction defaults, and alerting thresholds—along with common pitfalls to avoid, such as relying on averages, mistaking step count for tool calls, and treating cancelled or timed-out spans as successes.
From Single-Result Debugging to Batch-Level Visibility
When only one or two developers use an agent, debugging usually means inspecting the session UI and execution logs. If a result looks wrong, you replay that one conversation. But once usage scales, the nature of the problem changes. The team now cares about the distribution of task durations over a week, which task types have unusually high failure rates, whether the cost of a particular model is creeping up, and whether an interruption from a few days ago can be reproduced. These questions require data that spans sessions and machines and can be retained over long periods.
A local session view is designed for single-point observation, not aggregate statistics. Using it as a data source hits three constraints: data only covers a single machine; session data may be cleaned up or overwritten after the session ends; and field structures change across versions, making horizontal comparisons unreliable. This calls for a separate observability layer that converts agent execution into structured data and routes it to retrieval, aggregation, and alerting pipelines.
First, Understand the Execution Model
Most coding agents follow a ReAct-style loop. A single user request is called a turn. Within a turn, the agent executes a sequence of steps. Each step involves three actions: model reasoning, tool invocation, and observing the result. Since the model decides at runtime how many loops to run and which tools to call, two executions of the same task can produce completely different call chains.
This directly shapes the data design. If you pre-instrument a fixed pipeline, fields will be missing or misaligned. The correct approach is to let the collection layer follow execution events rather than assuming a predefined call graph. A typical hierarchy looks like this:
- Session: the user’s interaction context from start to finish; may contain multiple turns.
- Turn: a complete execution triggered by one user instruction.
- Step: one model invocation, plus the subsequent tool execution and result feeding back into context.
- Span (leaf operation): a model call, tool call, sandbox command, or external service request.
Once the hierarchy is clear, every metric can be computed at the right granularity. For example, per-task duration is calculated at the turn level, model cost at the model dimension, and tool failure rate at the tool_name dimension.
What Data to Collect
It is recommended to record at least the following fields for every leaf span:
| Field | Description | Primary Use |
|---|---|---|
session_id |
Session identifier | Correlate across turns |
turn_id |
Turn identifier | Task-level statistics |
step_index |
Step sequence number | Locate position in the loop |
span_type |
model, tool, sandbox, etc. |
Duration attribution |
start_ts, end_ts |
Start and end timestamps | Compute duration |
model_name |
Model identifier | Allocate cost per model |
input_tokens, output_tokens |
Input and output token counts | Cost analysis |
tool_name |
Tool name | Tool hotspots and failure rates |
status |
success, error, cancelled, timeout |
Failure analysis |
error_class, error_digest |
Error category and summary | Failure classification |
Below is an illustrative data structure showing how the collection layer might organize these fields:
import timeimport uuidfrom dataclasses import dataclass, fieldfrom typing import Optional@dataclassclass Span:session_id: strturn_id: strstep_index: intspan_type: str # model / tool / sandboxname: str # model identifier or tool namestart_ts: float = field(default_factory=time.time)end_ts: Optional[float] = Noneinput_tokens: int = 0output_tokens: int = 0status: str = "running"span_id: str = field(default_factory=lambda: uuid.uuid4().hex)def finish(self, status: str = "success",input_tokens: int = 0, output_tokens: int = 0) -> None:self.end_ts = time.time()self.status = statusself.input_tokens = input_tokensself.output_tokens = output_tokens@propertydef duration_ms(self) -> Optional[float]:if self.end_ts is None:return Nonereturn (self.end_ts - self.start_ts) * 1000
Timing matters when it comes to persistence. Spans should be written to disk synchronously at finish() time to avoid data loss from unexpected process exits. After a process recovers, spans still in the running state should be marked as incomplete rather than discarded outright—these records are exactly the clues needed for interruption analysis.
Latency Attribution: Inference vs. Tool Execution
The duration of a single turn can be broken down into three parts: model inference time, tool execution time, and everything else (scheduling and waiting). Only after this split can you direct optimization efforts effectively.
def summarize_turn(spans: list[Span]) -> dict:done = [s for s in spans if s.end_ts is not None]if not done:return {}wall_ms = (max(s.end_ts for s in done) - min(s.start_ts for s in done)) * 1000model_ms = sum(s.duration_ms for s in done if s.span_type == "model")tool_ms = merged_interval_ms([s for s in done if s.span_type == "tool"])return {"wall_ms": round(wall_ms),"model_ms": round(model_ms),"tool_ms": round(tool_ms),"other_ms": round(wall_ms - model_ms - tool_ms),}def merged_interval_ms(spans: list[Span]) -> float:# Time ranges of parallel tool calls may overlap; summing directly# would overestimate tool duration, so we merge intervals first.intervals = sorted((s.start_ts, s.end_ts) for s in spans)total, cur_start, cur_end = 0.0, None, Nonefor start, end in intervals:if cur_end is None or start > cur_end:if cur_end is not None:total += cur_end - cur_startcur_start, cur_end = start, endelse:cur_end = max(cur_end, end)if cur_end is not None:total += cur_end - cur_startreturn total * 1000
How to interpret the breakdown:
- High model time: check prompt length, context truncation strategy, model selection, and whether any reusable caching applies.
- High tool time: investigate sandbox startup duration, dependency installation, test suite runtime, and network latency to external services.
- High
othertime: usually points to scheduler queuing, serialization bottlenecks, or process startup overhead—issues to address at the runtime layer.
Cost Analysis: Attribution Dimensions for Token Consumption
Token costs are determined by the per-token input and output prices of each model. These prices vary by provider and plan, so analysis should follow the actual billing statements rather than assuming fixed numbers. Cost attribution can be approached along several dimensions.
First, split by model. Price differences across models can be substantial; switching models for the same task can change cost by multiples.
Second, split by step-count distribution within turns. Each step typically resends the accumulated context to the model. Without truncation, the cumulative input tokens for a turn grow super-linearly as steps increase. As a result, a small number of long-tail tasks with many steps often account for most of the cost. When reporting, look at percentiles of step counts, not just the mean.
Third, split by tool output size. Tool responses are stitched back into the context, so large log blocks or file contents significantly amplify the input size of every subsequent step. Recording the byte size or token count of each tool output lets you quickly locate cost amplification points.
Fourth, split by session and user. This dimension is useful for budget management and quota alerts, but be mindful of access control—personal usage details should not be exposed to unrelated personnel.
Failure and Interruption Tracing
Failure analysis aims to answer two questions: where the failure occurred and what the state looked like before it. It is recommended to classify failures into the following categories:
- Model-side errors: request timeout, rate limiting, output format not matching expectations, context exceeding the window length.
- Tool-side errors: command returns a non-zero exit code, permission denied, parameter validation failure, target resource not found.
- Sandbox-side errors: environment startup failure, resource limits exceeded, network policy blocking.
- Human interruption: the user actively cancelled.
- Policy-based termination: maximum step count reached, budget limit hit, or timeout threshold breached.
- Process anomaly: crash or system termination, visible as a
runningspan that never ends.
When tracing, restore the entire turn in step_index order, find the last successful step, then examine the input/output summary of the failed step. This reveals whether the failure is sporadic or structural. For example, if the same tool fails on identical parameters across multiple turns, the problem is in the tool or the prompt, not an occasional network hiccup.
Be careful about side effects when replaying. Tool calls may involve writing files, sending requests, or modifying databases. Replay analysis should read the already-recorded inputs and outputs rather than re-executing these tools, which could duplicate external effects.
Implementation Recommendations
- Make the collection layer non-invasive. Mount it as a plugin or hook in the execution framework—no changes to business logic, no dependence on a specific execution path.
- Tier the storage. Keep recent data in storage optimized for fast retrieval to serve alerting and same-day diagnosis; archive historical data to lower-cost media such as object storage for cost reviews and version comparisons.
- Redact by default. Prompts, source code, and tool outputs may contain internal code or credentials. By default, store only summaries, lengths, and hashes; make the original content accessible only with separate authorization.
- Set alert thresholds. Common indicators include: steps per turn exceeding a threshold, token usage per task over budget, failure rate notably higher than the previous week, and P95 duration exceeding the baseline.
- Record version tags. Write the agent version, model version, and prompt version into every span. Otherwise, you cannot determine whether a given change caused a shift in cost or success rate.
Common Pitfalls to Avoid
- Only looking at averages. Long-tail tasks typically account for most of the cost and duration. Percentiles reflect reality far better than means.
- Mistaking step count for tool call count. A step may consist of model reasoning only, with no tool invocation at all.
- Ignoring
cancelledandtimeout. If these are counted as successes, the real failure rate becomes invisible. - Using session IDs instead of task IDs. A session may contain multiple independent tasks; aggregate at the turn level.
- Relying only on post-hoc statistics. Cost and failure-rate anomalies often require minute-level alerting to handle in time; offline reports serve only for retrospectives.
