medium.com 8 min read Original Source

AI Agents Don’t Just Need Traces. They Need Semantic Telemetry.

A controlled simulation of a five-agent pipeline: 63 wrong SQL queries were approved by the critic and would have shipped as successful requests. Here’s why ordinary tracing can’t even measure that number.

A span in a microservice trace tells you two things: how long something took, and whether it succeeded. A span in an agent pipeline can report a clean success, no exception thrown, and still be wrong, because the work inside it was a judgment call, not a deterministic operation. The problem isn’t execution. It’s judgment.

Most existing advice on agent observability solves a real but different problem: which model was called, how many tokens it used, how long each step took. None of it tells you whether a critic agent was right to approve the thing it approved. I built a working five-agent pipeline, instrumented it with real OpenTelemetry spans, and ran it 300 times to measure that gap directly. The result surprised me: 63 incorrect SQL queries were approved by the critic and would have shipped as successful requests, with nothing on any dashboard to flag them.

The shape of the problem

Take a text-to-SQL pipeline built from five specialized agents: an intent parser that breaks the question into discrete analytical intents, a schema agent that maps those intents to real tables and columns, a query builder that generates SQL, a critic that checks the SQL against the original intents, and a response agent that formats the final answer. If the critic rejects a query, the pipeline loops back to the query builder with the critique attached, up to some retry limit. This shape mirrors a documented multi-agent architecture already running in production [4], and it’s the structure the experiment below is built around.

Architecturally, a pipeline like this is a distributed system the moment it has more than one independent component handing off state across a boundary, whether that boundary is a network call or a function call between two differently prompted LLM invocations. That’s not a metaphor, it’s the same shape as a microservice call chain: independent units, each with a narrow responsibility, handing state to the next one across a boundary. What matters is what a wrong answer from it actually costs. A misrouted schema mapping or a false-positive critique verdict doesn’t crash anything. It produces an answer that looks exactly like a correct one, and whatever gets decided from it downstream has no way to tell the difference until a support ticket arrives three days later and someone has to work out why.

What debugging looks like without tracing

Here’s a representative excerpt from the kind of log stream most teams have today:

[intent_parser] Running intent parser
[intent_parser] Output: [{"description": "rank customers by category", ...}]
[schema_agent] Mapping schema
[schema_agent] Output: {"customers": "dim_customer", ...}
[query_builder] Generating query, attempt 1
[query_builder] Output: SELECT customer_id, category, ...
[critic] Evaluating query
[critic] Output: {"passed": false, "issues": ["missing 12-month window filter"]}
[query_builder] Generating query, attempt 2
[query_builder] Output: SELECT customer_id, category, ...
[critic] Evaluating query
[critic] Output: {"passed": true}
[intent_parser] Running intent parser
[intent_parser] Output: [{"description": "rank customers by category", ...}]
[schema_agent] Mapping schema
[schema_agent] Output: {"customers": "dim_customer", ...}
[query_builder] Generating query, attempt 1
[query_builder] Output: SELECT customer_id, category, ...
[critic] Evaluating query
[critic] Output: {"passed": false, "issues": ["missing 12-month window filter"]}
[query_builder] Generating query, attempt 2
[query_builder] Output: SELECT customer_id, category, ...
[critic] Evaluating query
[critic] Output: {"passed": true}

Nothing here is timestamped in a way that lets you compute latency per agent, and there’s no link between a specific critic verdict and the specific query attempt it evaluated, beyond reading top to bottom and counting. Run two pipelines concurrently, which is normal in production, and their log lines interleave, and the excerpt above stops being reconstructable at all.

The failure mode from the opening is already sitting quietly inside this excerpt. The second critic verdict says passed: true. Nothing here tells you whether that verdict was correct, or how often verdicts like it are wrong across the thousands of runs this log stream represents. That second question, the rate question, is the one raw logs are structurally incapable of answering, and it’s worth proving that rather than asserting it.

Running the experiment

To isolate the observability problem from model quality, I replaced each LLM with a small, seeded deterministic function. The simulation measures how observability behaves under known conditions, not how accurate any specific model is. Each run has a chance of an injected bug in the generated query, drawn from four categories: a missing time-window filter, a wrong join, a wrong aggregation, or a wrong column reference. The critic catches each category at a different, deliberately unequal rate, modeling a specific claim: a critic checking SQL against stated intents is far better at catching structural problems than it is at catching the absence of an implicit constraint nobody stated outright, like a time window. These detection rates are assumptions built to model that asymmetry, not measurements from a production system.

Every span is real, backed by an actual OpenTelemetry TracerProvider. The part that matters is what gets attached to each one:

def run_pipeline(run_id):
    with tracer.start_as_current_span("pipeline_run") as root:
        root.set_attribute("run.id", run_id)
        # ... intent_parser and schema_agent spans omitted for brevity ...

        bug = pick_bug()  # None, or one of four categories, by weighted draw
        for attempt in (1, 2):
            with tracer.start_as_current_span("query_builder") as span:
                span.set_attribute("retry.attempt", attempt)
                span.set_attribute("bug.injected", bug or "none")

            with tracer.start_as_current_span("critic") as span:
                passed = critic_evaluates(bug)  # per-category detection probability
                span.set_attribute("critique.passed", passed)
                span.set_attribute("bug.actual", bug or "none")
                if passed:
                    break

            bug = maybe_fix_or_introduce_new_bug(bug)

        return {"run_id": run_id, "final_bug": bug, "final_passed": passed}
def run_pipeline(run_id):
    with tracer.start_as_current_span("pipeline_run") as root:
        root.set_attribute("run.id", run_id)
        # ... intent_parser and schema_agent spans omitted for brevity ...

        bug = pick_bug()  # None, or one of four categories, by weighted draw
        for attempt in (1, 2):
            with tracer.start_as_current_span("query_builder") as span:
                span.set_attribute("retry.attempt", attempt)
                span.set_attribute("bug.injected", bug or "none")

            with tracer.start_as_current_span("critic") as span:
                passed = critic_evaluates(bug)  # per-category detection probability
                span.set_attribute("critique.passed", passed)
                span.set_attribute("bug.actual", bug or "none")
                if passed:
                    break

            bug = maybe_fix_or_introduce_new_bug(bug)

        return {"run_id": run_id, "final_bug": bug, "final_passed": passed}

Every timestamp came from an actual span start and end recorded by the SDK. The only thing simulated is what a live LLM call would have returned.

The full simulation, including the parts trimmed here for length, is in this gist

The result

Out of 300 runs, 82 ended with a bug still present in the final query, and 63 of those were marked critique.passed: true. That number itself isn’t the point, the specific rate depends entirely on the detection probabilities I chose, and someone can reasonably argue different assumptions would give a different figure. The point is that this number exists at all. Traditional logs cannot compute an escape rate. Structured traces can. That capability, not the specific 76.8%, is what the experiment actually demonstrates.

Once you can measure it, the breakdown is where the real information lives:

Every single missing-time-window bug that survived to the final attempt did so with the critic’s approval. Wrong-column errors escaped only 23.1% of the time. A single top-level success rate would have averaged these into one meaningless number. Grouping by a bug.actual or critique.issues attribute is what turns “something is silently wrong sometimes” into “this specific category is nearly invisible to this specific critic,” which is the difference between a vague worry and an actionable finding.

That’s the actual thesis, demonstrated rather than asserted: the only reason any of the numbers above exist is that every run emitted structured, filterable attributes. Try computing an escape rate, or which category it’s concentrated in, from the raw log excerpt shown earlier. You’d be reading thousands of log files by hand, and you still wouldn’t know which category to look for, because nothing in that excerpt tells you a category exists.

Here’s what one specific run actually looked like, pulled directly from the captured trace data, not redrawn by hand:

Run 12 took two attempts. The first was correctly rejected. The second one, still carrying the same unresolved bug, one time-window check away from correct, was approved. The red bar is the exact moment this specific run’s answer became a silent failure, and it’s visible here only because bug.actual and critique.passed were attributes on the span rather than words in a sentence.

The infrastructure for this already exists

Distributed systems had this exact debugging problem for years before agents existed. A request enters through an API gateway, touches an auth service, an order service, an inventory service, and a payment service, and comes back slow or wrong. Before anyone fixed this properly, the standard technique was to open several log files and align them by wall-clock timestamp, hoping the clocks were synchronized closely enough to trust the ordering.

Google’s Dapper paper, published in 2010, is usually credited as the point where the industry standardized a real fix [1]. Generate one trace ID per incoming request, propagate it through every service that request touches, and record each unit of work as a span with a start time, an end time, a parent span, and structured attributes. A trace becomes a tree, renderable as a waterfall that shows exactly which hop was slow, which hop errored, and what the request looked like at each step, which is precisely the diagram above, just applied to five agents instead of five microservices.

The W3C later standardized how a trace ID crosses a network boundary, through a header called traceparent, so tracing works across services built by different teams on different stacks without everyone agreeing on a proprietary format first [2]. OpenTelemetry is the vendor-neutral instrumentation layer implementing both ideas, exporting to whatever backend renders the result: Jaeger, Zipkin, Honeycomb, or the in-memory exporter used for this experiment.

What a production version of this looks like

The instrumentation pattern is identical to the simulation, just with a real model call in place of the deterministic function:

def query_builder_node(state):
    with tracer.start_as_current_span("query_builder") as span:
        span.set_attribute("retry.attempt", state["retry_count"])
        previous = state.get("critique")
        if previous and not previous.get("passed"):
            span.set_attribute("retry.previous_rejection_reason",
                                "; ".join(previous.get("issues", [])))
        response = llm.invoke([system, human])
        span.set_attribute("llm.output_tokens",
                            response.usage_metadata.get("output_tokens", 0))
        return {"generated_query": response.content.strip()}

def critic_agent_node(state):
    with tracer.start_as_current_span("critic") as span:
        response = llm.invoke([system, human])
        critique = json.loads(response.content)
        span.set_attribute("critique.passed", critique["passed"])
        if not critique["passed"]:
            span.set_attribute("critique.issues", "; ".join(critique.get("issues", [])))
        return {"critique": critique, "retry_count": state["retry_count"] + 1}
def query_builder_node(state):
    with tracer.start_as_current_span("query_builder") as span:
        span.set_attribute("retry.attempt", state["retry_count"])
        previous = state.get("critique")
        if previous and not previous.get("passed"):
            span.set_attribute("retry.previous_rejection_reason",
                                "; ".join(previous.get("issues", [])))
        response = llm.invoke([system, human])
        span.set_attribute("llm.output_tokens",
                            response.usage_metadata.get("output_tokens", 0))
        return {"generated_query": response.content.strip()}

def critic_agent_node(state):
    with tracer.start_as_current_span("critic") as span:
        response = llm.invoke([system, human])
        critique = json.loads(response.content)
        span.set_attribute("critique.passed", critique["passed"])
        if not critique["passed"]:
            span.set_attribute("critique.issues", "; ".join(critique.get("issues", [])))
        return {"critique": critique, "retry_count": state["retry_count"] + 1}

In production you won’t have a bug.actual field, because you don’t have ground truth the way a simulation does. What you’d have instead is exactly what this experiment used to find the pattern in the first place: critique.issues text you can cluster, retry.attempt counts you can filter on, and a small manually-audited sample of traces, the production equivalent of knowing the simulation’s answer key, that lets you estimate a real escape rate for your own critic and your own bug categories.

The obvious objection: use LangSmith or Langfuse instead

LangSmith, Langfuse, and Arize Phoenix already give trace visualization for LLM pipelines out of the box, including custom metadata fields, without manual span wrapping. Why hand-roll it?

The advantage isn’t that these tools can’t record critique.passed and bug.actual. They can; these platforms let you attach arbitrary metadata to a run. Deciding that those are the fields worth recording for this pipeline is a judgment call someone has to make regardless of which product renders the resulting trace. No tool makes that decision for you, OpenTelemetry included.

What OpenTelemetry buys instead is portability. Instrument with vendor-neutral spans, and the same attributes can go to a hosted vendor UI, a self-hosted Jaeger instance, or both, without re-instrumenting the pipeline if the backend changes later. Several LLM-specific tracing products already accept OpenTelemetry-formatted spans directly, so the choice of instrumentation doesn’t lock you into the choice of viewer. OpenTelemetry maintains semantic conventions for generative AI systems specifically to standardize this kind of attribute across frameworks and vendors [3].

Unstructured logs against a traced pipeline

The cheap version, if full tracing is too much right now

A single generated run_id, created once at the start of a pipeline run and threaded through every state dict and log line, gets you most of the concurrent-runs problem for a fraction of the effort:

dict:
return {"run_id": str(uuid.uuid4()), "user_query": user_query, "retry_count": 0}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

import uuid

def start_pipeline(user_query: str) -> dict:
    return {"run_id": str(uuid.uuid4()), "user_query": user_query, "retry_count": 0}
import uuid

def start_pipeline(user_query: str) -> dict:
    return {"run_id": str(uuid.uuid4()), "user_query": user_query, "retry_count": 0}

This won’t give you a waterfall diagram or the category breakdown shown above. It will let you grep a log stream for one run_id and get exactly the lines that belong to one run, with everything else filtered out. For a two- or three-agent pipeline with no retry loop, that’s not a stopgap, it’s the right amount of instrumentation for what that pipeline can actually get wrong. The case for full spans and structured attributes gets stronger in direct proportion to how many independent decisions the pipeline makes and how often it retries them.

The principle

Traditional observability records operational telemetry: latency, throughput, errors. Agent systems introduce a kind of state that has no analogue in ordinary distributed systems, a critique verdict, a retry reason, a confidence level, and that state has no home in a trace built only to record whether a call succeeded. Observability for agents has to capture semantic telemetry alongside the operational kind, or it will keep reporting a pipeline as healthy while it quietly ships wrong answers underneath.

Microservices already built the tooling to trace a system of independent, handoff-heavy components. What they never had to solve is the part agent pipelines can’t skip: recording why a model believed a wrong answer was acceptable, not just whether the call that produced it succeeded. In this experiment, that gap wasn’t hypothetical. It was measurable the moment the trace carried the right attributes, and invisible the moment it didn’t.

References

[1] B. H. Sigelman et al., Dapper, a Large-Scale Distributed Systems Tracing Infrastructure (2010), Google Technical Report

[2] World Wide Web Consortium, Trace Context (2021), W3C Recommendation

[3] OpenTelemetry Authors, Semantic Conventions for Generative AI Systems, OpenTelemetry Documentation

[4] P. Bhardwaj, Why I Stopped Using One Agent and Built a Multi-Agent Pipeline Instead (2026), Towards Data Science