A hands-on guide to tracing AI agents with OpenTelemetry, span design, and SDK-level instrumentation for production systems.
Agent TracingLong read

What Span-Level Instrumentation Data Actually Powers Automatic Failure Pattern Grouping

Tool arguments, outputs, and span links let clustering find root causes.

· 8 min read
Cover illustration for “What Span-Level Instrumentation Data Actually Powers Automatic Failure Pattern Grouping”
Agent Tracing · November 24, 2026 · 8 min read · 1,850 words

To group recurring AI agent failure patterns automatically, the pipeline needs span-level evidence as well as error logs. Tool arguments, model outputs, retrieval chunks, and parent-child links let evaluators identify failures and clustering layers group them by cause. The pipeline runs from structured spans through scoring and embeddings to named issues, with enough context to assign a fix and turn the failure into a regression test.

Why span data is the foundation of failure grouping, not just logging

A dashboard can be green while the agent gives the wrong answer. If the agent picks the wrong tool and returns a successful HTTP response, transport monitoring counts it as a success. It does not establish that the task was completed correctly. Semantic failures can happen without an error code. A hallucinated identifier, a wrong policy citation, or a loss of context requires evaluation of what happened inside the request.

The span is the atomic unit of that execution. Every tool call, model invocation, retrieval step, and guardrail check should have its own structured span so it can be seen within a top-level HTTP event. Traditional APM without LLM-specific instrumentation cannot expose those internal operations, although Datadog, New Relic, and Grafana have launched dedicated agent or LLM observability products that do. Because a failure is often visible only in the final answer, the trace must connect that symptom to the operation that introduced it.

The span fields that carry groupable signal

The root span keeps the overall status and wall-clock duration of the workflow. An LLM span records the model name, input and output tokens, finish reason, raw prompt, and raw completion. A tool span records the tool name, full argument payload, raw output, and error type if one exists. A retriever span records the query string, top-k chunks with their scores, and source identifiers.

Tool arguments reveal whether the agent constructed valid parameters, while the raw tool output separates a bad request from a valid request that returned bad data. The completion gives evaluators the text needed to assess faithfulness, instruction adherence, and hallucination. Retrieval chunks provide the evidence against which that text is judged. Latency and token counts cannot make those comparisons.

Finish reason supplies another distinction, with stop, length, tool_calls, and content_filter separating natural completion, truncation, tool invocation, and filtering. Trace ID, span ID, and parent span ID connect these records into an execution tree. OpenTelemetry GenAI semantic conventions define attributes under development for model, prompt, response, tokens, and finish reason, supporting portability across backends. That standardization gives a clustering layer a predictable schema, although the semantic evidence still depends on capturing the content.

How parent-child linkage turns isolated spans into a traceable execution tree

Parent-child linkage makes a failure’s propagation path traceable. In a multi-agent workflow, the parent span ID connects a child agent’s execution to the agent that delegated the task. Without that relationship, a sub-agent’s tool failure and the final wrong answer can appear unrelated. The structure preserves the path between them. An error-propagation view can then mark parents that inherited a child’s failure state and highlight downstream spans that consumed the failed output.

A customer support trace begins with triage_agent routing to order_lookup_agent, which calls order_api and formats the returned data. The triage agent then routes to response_agent. If order_api returns stale data, that error goes through more processing before it reaches the user as a wrong answer.

The investigation can establish whether response_agent misinterpreted the result, whether order_lookup_agent supplied correct data, and whether order_api returned fresh information. Logging exceptions at every level cannot substitute for this structure because stale data need not raise an exception. Content evaluation must expose that silent failure.

What the scoring layer does with span content before clustering can begin

In this pipeline, scoring identifies which executions failed and how. An evaluator attaches to sampled production traces, or traces flagged by guardrails or low-confidence signals, and writes scores onto spans as attributes. Faithfulness compares the LLM output with the upstream retrieval chunks. Tool correctness compares argument payloads with the tool schema and expected behavior, exposing malformed arguments or wrong-tool selection. Each rubric depends on a different piece of evidence.

Instruction adherence compares the agent’s output with the original system prompt to detect policy violations and goal drift. Plan quality and step efficiency check the execution path for loops, over-retrieval, and tool calls that repeat work. These scores describe more than success or failure. They separate dimensions of quality that can require different interventions, even when the final answers look similar. Scoring thus shows what failed before embeddings show how the failures are alike.

The judge’s access determines what it can evaluate. A judge that sees only the final answer cannot inspect tool arguments, retrieval evidence, or intermediate reasoning, whereas an agent-as-judge with trace access can compare individual LLM spans with their upstream evidence. Access does not guarantee correct diagnosis, however. Patronus AI’s 2025 TRAIL benchmark found that even the best evaluated model localized issues in only a minority of expert-annotated traces. Automated trace evaluation remains imperfect, so its scores are evidence for investigation.

How span embeddings and HDBSCAN automatically group recurring agent failures

Diagram: From Raw Spans to Named Issues: The Pipeline Flow. Visualizes: The article describes a sequential pipeline with five distinct stages: (1) structured spans — root, LLM, tool, retriever spans with parent-child links; (2) a scoring layer —…

The clustering layer uses embeddings of span content alongside scores. Scores identify the failure dimensions, while vector representations of tool arguments, model outputs, and retrieval context capture similarities across executions. Failures can thus end up in the same group even when they are worded differently. In this pipeline, failing traces and their span embeddings go into ClickHouse before the clusters are investigated.

HDBSCAN works when the types of failure are not known ahead of time. Unlike k-means, it does not require a predetermined cluster count or force every point into a group. It discovers groups from data density and marks noise points separately. That distinction preserves room for unfamiliar failures. A fixed taxonomy can label known classes, but it cannot by itself discover how new production failures congregate.

Each cluster then triggers a judge agent that investigates spans through tools including read_span, get_children, get_spans_by_type, and search_spans. The judge submits findings, scores, and a summary, with a lighter summarizer handling spans above a character threshold to control token cost. Its outputs include a taxonomy classification, a multi-dimensional trace score, and an immediate_fix string identifying a candidate change. A named issue such as “CRM API timeout — retry loop” combines an occurrence count, a root-cause span, and a proposed fix. Scale AI’s interaction-centric taxonomy study reported Cohen’s κ = 0.76 for automated failure-mode labeling against human labels, evidence of useful agreement without implying perfect diagnosis.

The failure modes that span data must distinguish for clustering to be useful

Failures that need different fixes must go into different groups. Malformed tool arguments are visible in the structured payload, while correct arguments followed by bad data require inspection of the tool’s raw output. To spot wrong-tool selection, the tool name and the context of the task are needed. These are not interchangeable tool errors. Grouping them just by a final wrong answer would hide the differences needed to fix them.

Irrelevant chunks point to the retrieval step, while a completion that contradicts relevant chunks points to a failure of faithfulness. The query, chunks, scores, and source identifiers make that comparison possible. An output cut short by length and one blocked by content_filter can both leave the task incomplete, but they do not describe the same failure.

Repeated tool spans expose retry loops, while the prompt and output support evaluation of instruction adherence and goal drift. Parent-child links keep the context needed to trace failures across agent handoffs. The CODS 2025 AssetOpsBench Challenge identified “Lack of Final Answer,” “Inadequate Error Handling,” and “Lack of Contextual Understanding” as its top three failure-mode labels, consistent with process-level weaknesses. Stable accuracy can coexist with sharply declining output diversity. Span-level evaluation therefore needs multiple quality dimensions, including error rate.

How the interaction-centric view determines whether the fix belongs to the model or the harness

Scale AI’s Model or Harness? An Interaction-Centric Taxonomy for Localizing Agent Failures frames diagnosis as a repair-assignment problem. Agent behavior emerges from interactions among the model, harness, users, tools, memory, and environment. A wrong final answer does not identify which component needs to change. The origin of the failure is decisive. Span-level evidence lets the investigation move from an outcome label to the interaction where the repair belongs.

A malformed tool payload can call for a schema constraint or a prompt edit. Irrelevant retrieval chunks can call for a configuration change or query rewriting. When a completion contradicts the system prompt even though retrieval was correct, it may need model fine-tuning or a stronger instruction hierarchy. Wrong routing to a child agent instead points to harness routing logic. Planning and handoff spans can supply the relevant routing evidence without treating the enclosing agent span as a record of every decision.

Misassignment becomes especially costly when errors propagate across agents. A failure originating in a sub-agent’s tool can lead a team to retrain the top-level model if the investigation stops at the final answer. The CRM example illustrates that diagnostic trap. Its visible failure was a wrong escalation decision, but its root cause was missing retry backoff in the CRM tool wrapper. The needed intervention was a harness fix.

Turning production failure clusters into regressions that evals catch automatically

Diagram: The Corrective Loop: Cluster → Regression → Gate. Visualizes: The article describes a four-step corrective loop that closes the gap between production failures and future prevention: (1) identify root-cause span from a named cluster; (2)…

A named cluster can help catch failures over time when its evidence is turned into an eval. The corrective loop identifies the root-cause span, reproduces the scenario, changes the prompt, tool schema, or workflow, and gates the fix on a new test. The data from the failing span sets the conditions for the test. Without that new test, fixing the current issue leaves no automatic way to catch it if it returns.

The CRM case turns the production pattern into a concrete regression scenario. The API returns 504 on the first three calls and then 200, while the expected behavior is escalation to human handoff after three attempts. Evidence from production showed that the retry loop had fired 11 times in each session before escalation. The test therefore evaluates the agent’s handling of repeated failure. It preserves the process requirement that the original execution violated.

Online evals apply the original rubric to new production spans. The sampling pattern covers traces flagged by guardrails or low-confidence signals and a small sample of the full stream to control cost. This keeps detection tied to live behavior. Static suites built before production cannot foresee every failure mode that comes from real use, so cases drawn from clusters update the eval set as those patterns appear in production spans.

Routing completes the operational loop by sending the named issue to Slack, Linear, or a coding agent through MCP. The issue includes a dashboard pointer, the score breakdown, failing trace, root-cause span, and immediate_fix string. A coding agent with that context can draft a prompt patch or tool schema change and open a PR. Engineers receive evidence that supports a specific intervention. The proactive goal is to surface recurring patterns as they accumulate, before further users encounter them, rather than wait for user reports or a manually configured threshold.

Sources

  1. Model or Harness? An Interaction-Centric Taxonomy for Localizing Agent Failures
  2. Results and Retrospective Analysis of the CODS 2025 AssetOpsBench Challenge
  3. What Resolve Rate Hides: Trajectory Structure Diagnostics for Coding Agents
Filed underAgent Tracing

More in Agent Tracing