DEV Community

Cover image for Your Agent Returned 200 OK and Still Got It Wrong: A Developer's Guide to Tracing Multi-Step Agent Failures
mech.app
mech.app

Posted on Originally published at mech.app

Your Agent Returned 200 OK and Still Got It Wrong: A Developer's Guide to Tracing Multi-Step Agent Failures

Your refund agent approved a transaction outside the 30-day policy window. The customer is happy. Finance is furious. You check your dashboards: error rate normal, p95 latency normal, HTTP 200 across the board. The final message was polite and well-formatted. Everything looks green.

The bug lives three steps earlier in the execution chain. A bad retrieval, a misread tool result, or a policy check that failed silently. Your APM can't see it. Your LLM token counter can't see it. Only a trace can.

This is the observability gap between traditional API monitoring and agentic execution. HTTP success codes tell you the plumbing worked. They don't tell you if the agent made the right decision.

The Silent Failure Problem

Agents fail differently than APIs. An API either returns the data or throws an error. An agent can retrieve the wrong document, misinterpret a tool response, skip a validation step, and still produce a confident, well-formatted answer.

The failure modes:

  • Retrieval drift: The agent pulls documents that match keywords but miss context
  • Tool hallucination: The agent invents tool arguments or misreads JSON responses
  • Policy bypass: The agent skips a validation step because the LLM didn't recognize it as mandatory
  • State corruption: Multi-step workflows lose context between hops

None of these throw exceptions. They all return 200 OK.

What Agent Observability Actually Captures

Agent observability reconstructs the full decision chain after the fact. You need four signals:

Signal What It Captures Example
Traces The full execution path split into spans classify → retrieve → check_policy → issue_refund
Metrics Aggregated numbers over many runs Task success rate, cost per task, tool error rate
Logs Step-level events and raw payloads The exact prompt, retrieved chunks, raw tool JSON
Evaluations Scores judging correctness Did the agent follow policy? Was the refund valid?

Traditional APM gives you traces and metrics for HTTP requests. Agent observability extends that to LLM calls, tool invocations, retrieval steps, and decision branches.

Instrumenting an Agent with OpenTelemetry

OpenTelemetry GenAI semantic conventions define how to structure spans for LLM and agent workflows. Each span captures one logical step.

Core Span Structure

from opentelemetry import trace
from opentelemetry.semconv.ai import SpanAttributes

tracer = trace.get_tracer(__name__)

def agent_step(task_input):
    with tracer.start_as_current_span(
        "agent.classify_intent",
        kind=trace.SpanKind.INTERNAL,
        attributes={
            SpanAttributes.GEN_AI_SYSTEM: "openai",
            SpanAttributes.GEN_AI_REQUEST_MODEL: "gpt-4",
            SpanAttributes.GEN_AI_REQUEST_TEMPERATURE: 0.0,
            "agent.task_id": task_input["id"],
            "agent.step": "classify",
        }
    ) as span:
        response = llm.classify(task_input["text"])

        span.set_attribute(SpanAttributes.GEN_AI_RESPONSE_ID, response.id)
        span.set_attribute(SpanAttributes.GEN_AI_USAGE_INPUT_TOKENS, response.usage.prompt_tokens)
        span.set_attribute(SpanAttributes.GEN_AI_USAGE_OUTPUT_TOKENS, response.usage.completion_tokens)
        span.set_attribute("agent.decision", response.intent)

        return response
Enter fullscreen mode Exit fullscreen mode

What Every Span Must Include

For post-mortem debugging, each span needs:

  • Task context: Unique task ID, user ID, session ID
  • Step identity: Which agent, which tool, which decision point
  • Input snapshot: The exact prompt or tool arguments sent
  • Output snapshot: The raw response before any parsing
  • Decision metadata: Why the agent chose this path (if available from chain-of-thought)
  • Tool results: The actual data returned by external APIs

The mistake most teams make: logging only the final answer. You need the intermediate states.

Trace Propagation Across Agent Boundaries

Multi-agent systems hand off tasks between specialized agents. Trace context must flow across these boundaries without coupling agents to a specific observability backend.

W3C Trace Context Headers

When Agent A calls Agent B via HTTP:

from opentelemetry.propagate import inject

def call_specialist_agent(task_data):
    headers = {}
    inject(headers)  # Injects traceparent and tracestate

    response = requests.post(
        "https://specialist-agent/api/task",
        json=task_data,
        headers=headers
    )
    return response.json()
Enter fullscreen mode Exit fullscreen mode

Agent B extracts the context:

from opentelemetry.propagate import extract

def handle_task(request):
    ctx = extract(request.headers)
    with tracer.start_as_current_span("specialist.process", context=ctx):
        # This span is now a child of Agent A's span
        result = process_task(request.json)
        return result
Enter fullscreen mode Exit fullscreen mode

For message queues or async workflows, serialize trace context into the message payload:

from opentelemetry.trace import get_current_span
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator

def enqueue_task(task):
    carrier = {}
    TraceContextTextMapPropagator().inject(carrier)

    queue.send({
        "task": task,
        "trace_context": carrier
    })
Enter fullscreen mode Exit fullscreen mode

Structured Logging Schema for Decision Chains

Traces give you the shape of execution. Logs give you the content. The schema needs to capture both the agent's reasoning and the external tool results.

Minimal Decision Log

{
  "timestamp": "2026-11-23T00:04:50Z",
  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
  "span_id": "00f067aa0ba902b7",
  "agent": "refund_processor",
  "step": "policy_check",
  "input": {
    "order_id": "ORD-12345",
    "order_date": "2026-09-15",
    "request_date": "2026-11-23"
  },
  "tool_call": {
    "name": "check_refund_eligibility",
    "arguments": {
      "order_id": "ORD-12345",
      "days_since_order": 69
    }
  },
  "tool_result": {
    "eligible": false,
    "reason": "exceeds_30_day_window",
    "policy_link": "https://policy.example.com/refunds"
  },
  "agent_decision": "approve_refund",
  "reasoning": "Customer has been loyal for 3 years, making exception",
  "policy_override": true
}
Enter fullscreen mode Exit fullscreen mode

The critical field: tool_result vs agent_decision. When they diverge, you have a semantic failure.

Reconstructing Decision Trees Without Re-Running

Post-mortem analysis needs to answer: "Why did the agent make this choice?" without replaying the entire workflow.

Query Pattern for Decision Divergence

If you're storing logs in a queryable backend (Elasticsearch, ClickHouse, BigQuery):

SELECT 
  trace_id,
  step,
  tool_result->>'eligible' as tool_says,
  agent_decision,
  reasoning
FROM agent_logs
WHERE 
  agent = 'refund_processor'
  AND tool_result->>'eligible' = 'false'
  AND agent_decision = 'approve_refund'
ORDER BY timestamp DESC
LIMIT 100;
Enter fullscreen mode Exit fullscreen mode

This surfaces every case where the agent overrode a tool's negative result.

Span Linking for Multi-Path Exploration

When an agent explores multiple options (like trying three different retrieval strategies), link the exploratory spans to the final decision span:

from opentelemetry.trace import Link

def explore_and_decide(query):
    exploration_spans = []

    for strategy in ["semantic", "keyword", "hybrid"]:
        with tracer.start_as_current_span(f"explore.{strategy}") as span:
            results = retrieve(query, strategy)
            exploration_spans.append(Link(span.get_span_context()))

    with tracer.start_as_current_span(
        "decide.final_answer",
        links=exploration_spans
    ):
        final_answer = synthesize(exploration_spans)
        return final_answer
Enter fullscreen mode Exit fullscreen mode

The final span links back to all exploration attempts. You can see which retrieval strategy influenced the decision.

Sampling and Redaction

Full trace capture for every agent run is expensive and often contains PII. You need sampling and redaction rules.

Adaptive Sampling Strategy

from opentelemetry.sdk.trace.sampling import ParentBasedTraceIdRatioBased, ALWAYS_ON

def custom_sampler(span_context, attributes):
    # Always sample if error or policy override
    if attributes.get("error") or attributes.get("policy_override"):
        return ALWAYS_ON

    # Sample 10% of routine tasks
    return ParentBasedTraceIdRatioBased(0.1)
Enter fullscreen mode Exit fullscreen mode

Redacting Sensitive Fields

def redact_pii(span_attributes):
    sensitive_keys = ["customer.email", "customer.ssn", "payment.card_number"]

    for key in sensitive_keys:
        if key in span_attributes:
            span_attributes[key] = "[REDACTED]"

    return span_attributes
Enter fullscreen mode Exit fullscreen mode

Apply redaction at span creation, not at query time. Once PII hits your observability backend, it's too late.

Five-Question Debugging Checklist

When an agent produces the wrong outcome:

  1. What was the agent asked to do? (Check the root span's input attributes)
  2. What tools did it call, and what came back? (Check tool invocation spans and their result attributes)
  3. Did any tool return an error the agent ignored? (Filter spans where tool.error exists but execution continued)
  4. What documents or context did retrieval surface? (Check retrieval span attributes for document IDs and relevance scores)
  5. Where did the agent's decision diverge from tool recommendations? (Compare tool_result fields to agent_decision fields in logs)

If you can't answer these five questions from your traces and logs, your instrumentation is incomplete.

Failure Mode Taxonomy

Failure Type Symptom Trace Signature
Retrieval miss Agent answers without key context Low relevance scores in retrieval span, no document IDs matching ground truth
Tool hallucination Agent invents tool arguments Tool span has error: invalid_arguments, agent continues anyway
Policy bypass Agent skips validation Missing span for policy check step, or policy span returns false but execution continues
State loss Agent forgets earlier context Span attributes missing expected context fields from parent spans
Timeout cascade Agent retries until success, ignoring quality Multiple retry spans with increasing latency, final span has degraded output

Technical Verdict

Use this approach when:

  • You're running multi-step agents in production where mistakes have business impact
  • You need to debug agent decisions after the fact without replaying workflows
  • You're orchestrating multiple specialized agents that hand off tasks
  • You need to prove compliance or audit agent behavior

Avoid or defer when:

  • You're still prototyping agent logic and iteration speed matters more than observability
  • Your agent is a single LLM call with no tools or retrieval (standard LLM monitoring is enough)
  • You don't have a queryable log backend (structured logs are useless if you can't search them)

The cost is instrumentation overhead and storage for traces and logs. The payoff is the ability to answer "why did the agent do that?" without guessing. For production agents making decisions with consequences, that's not optional.

Source Links

Top comments (0)