Observability for AI Agents at Scale: Tracing, Cost, and Failure Attribution

    This article explains why single-session debugging views are no longer enough once coding agents move into daily production workflows, and what platform-level observability requires instead. It defines four core entities to collect (turn, step, model call, tool call), shows how to link them into a trace tree, and argues for low-intrusion collection through native plugins rather than kernel changes. It then covers latency attribution, token cost allocation by session and model, failure and interruption traceability, and a four-stage rollout path with engineering caveats on async reporting, data masking, and storage tiering.

    Observability for AI Agents at Scale

    1. What Changes Once You Scale

    Coding agents are now part of the daily development workflow for many teams. During the trial phase, evaluation usually comes down to a single question: was this output correct, and did it run? Once call volume, concurrent sessions, and the number of participants all climb, attention shifts quickly to three more engineering-oriented questions:

    1. Where is the time actually going: is model inference slow, or is tool execution (compilation, tests, retrieval, external API calls) slow?
    2. Where is token consumption concentrated: which sessions, which models, and which task types consume most of the quota?
    3. Where do failures and interruptions happen: can the run be traced back, and can the context at that moment be reproduced without re-running?

    These three questions share one trait: none of them can be answered by looking at a single result one more time. They require structured trace data that spans sessions and machines and is retained over the long term. That is exactly what observability addresses, and it is not merely a matter of printing logs.

    2. Why a Single-Machine Session View Is Not Enough

    Mainstream open-source coding agent frameworks typically ship with session trajectory views, event stream persistence, and tool call retrieval. These capabilities are valuable, but their scope has three natural boundaries:

    • Local: data lands on the execution machine, so whoever investigates must be able to log into that machine;
    • Single session: the view is organized around one session and cannot compare a batch of tasks side by side;
    • Real time: it suits debugging something “happening now,” not reviewing something that “happened days ago.”

    As soon as the requirement becomes “see the overall behavior of a batch of tasks,” “see the cost distribution over a period,” or “reproduce a failure from three days ago,” the local single-session real-time view breaks down. The key point to recognize: a single-machine debugging view and platform-level observability are not substitutes. They are two layers of capability with different scopes. The former serves the developer’s immediate coding experience; the latter serves team-level efficiency and cost governance.

    3. Four Core Entities to Collect

    To reconstruct the execution process as a structured call chain, start by defining the data model clearly. The execution model of a coding agent is usually a ReAct loop: one end-to-end user request is a turn, and each round of “reason, call a tool, observe the result” inside that turn is a step. On that basis, the collection side needs to cover at least four entity types and their relationships:

    Entity Meaning Key fields (illustrative)
    Task/session (turn) One end-to-end user request Session ID, requester, start/end time, total duration, total tokens, final status
    Reasoning round (step) One loop iteration within a turn Step index, input summary, model name, inference duration
    Model call One actual model request Prompt tokens, completion tokens, time to first byte, total latency, error code
    Tool call One tool/command execution Tool name, call argument summary, return summary, execution duration, exit status

    The four entity types are linked through the parent-child relationship of trace/span, which forms the complete tree of “one task, multiple reasoning rounds, several tool calls per round.” Only with this tree in place do latency breakdown and failure localization have something to anchor to.

    1. turn (session)
    2. └── step#1 (reasoning round)
    3. ├── model_call
    4. └── tool_call
    5. └── step#2
    6. ├── model_call
    7. └── tool_call

    4. Low-Intrusion Collection: Why a Plugin Fits Better

    Open-source coding agent frameworks are commonly organized as a “microkernel plus full plugin” architecture: the kernel only assembles plugins according to a profile and manages their lifecycle, while model adapters, tool sets, sandbox policies, and session persistence are all pluggable. The CLI, the terminal UI, and the headless mode share the same kernel.

    This leads to an important engineering conclusion: observability should be mounted at the plugin layer and integrated as a native plugin, rather than by modifying the kernel or business code. The benefits are:

    • Zero business intrusion: the agent’s behavior logic and prompts stay unchanged;
    • Form-factor agnostic: all three runtime modes share one collection logic;
    • Toggleable: a profile decides whether collection is enabled in a given environment;
    • Upgradable: collection logic evolves independently and is not tied to the framework version.

    For the implementation, hook pre- and post-hooks of the model adapter and tool calls into the plugin lifecycle, enrich the event stream with structured fields, then report asynchronously in batches to a remote collection endpoint so that synchronous reporting never blocks the main execution path.

    1. {
    2. "trace_id": "t-8f3a...",
    3. "span_id": "s-02",
    4. "parent_span_id": "s-01",
    5. "name": "tool_call:run_tests",
    6. "start_time": 1730000000000,
    7. "duration_ms": 4210,
    8. "attributes": {
    9. "agent.turn_id": "turn-42",
    10. "agent.step": 2,
    11. "tool.name": "run_tests",
    12. "tool.exit_code": 1,
    13. "llm.tokens_prompt": 12043,
    14. "llm.tokens_completion": 386,
    15. "llm.model": "default-chat-model"
    16. }
    17. }

    5. Latency Attribution: Breaking Total Time into Actionable Parts

    With trace data available, latency analysis means decomposing the total turn duration in layers:

    turn duration ≈ Σ step inference time + Σ tool execution time + gaps (queueing, network, serialization)

    Three conclusions come up often in practice, along with the direction to take:

    • Inference dominates: usually overly long context or redundant rounds. Tune the context trimming strategy, cut ineffective rounds, and merge tool calls.
    • Tool execution dominates: usually heavy operations such as tests, builds, and dependency installation. Introduce caching, parallelize, and narrow the execution scope.
    • Gaps dominate: usually serial waiting and scheduling queues. Raise the concurrency level and parallelize model calls and tool calls that have no dependencies between them.

    One point deserves emphasis: do not look at averages only. The value of trace data is that you can inspect P50/P90/P99 and long-tail samples, and long-tail tasks are often the real bottleneck for both experience and cost.

    6. Cost Attribution: Tokens Must Map Back to Sessions and Models

    The prerequisite for token cost governance is that cost can be allocated. Record the prompt and completion tokens, model identifier, and the owning session and task tags (such as project, repository, task type) for every model call as fixed collection fields. With these dimensions you can answer:

    • Which project or repository consumes the most tokens;
    • Which task type (generation, refactoring, troubleshooting) is most expensive per unit of output;
    • How cost-effectiveness differs across models on the same task;
    • Whether anomalous sessions exist (repeated retries, or sudden spikes from oversized context).

    Combined with monitoring alerts and dashboards, you can set session-level and project-level token threshold alerts, moving cost governance forward from “reviewing the bill at month end” to “being able to intervene the same day.”

    7. Failures and Interruptions: Traceability Beats Re-running

    The failure modes of coding agents are scattered: the model returns an invalid tool call, a tool times out, a command exits non-zero, a sandbox policy blocks the action, the context exceeds its limit, or an upstream service rate-limits. Recording only the final status makes investigation extremely costly. The recommendations:

    1. A unified status enumeration: define explicit statuses and error codes for turns and steps, separating responsibility boundaries across “model side,” “tool side,” and “platform side.”
    2. Retain key context summaries: record truncated summaries of arguments and returns, balancing inspectability against protection of sensitive information.
    3. Support trace retrieval: combine session ID, error code, tool name, and time window to quickly narrow down the same class of failures.
    4. Sampled retention: raise the sampling rate for failed traces or retain them in full, and downsample successful traces to control storage cost.

    8. Rollout Path and Caveats

    A four-step progression avoids a large one-off rewrite:

    • Step 1: get collection working. Integrate as a plugin, and first make sure all four entity types (turn/step/model/tool) are complete and the parent-child relationships are correct.
    • Step 2: build the views. Start with single-session trace details, then add an aggregated dashboard for batch tasks.
    • Step 3: wire up alerts. Configure threshold alerts around failure rate, P99 latency, and token spikes.
    • Step 4: close the loop. Turn frequent failures into optimization items for prompts, tool sets, or sandbox policies.

    Three engineering points still need attention: first, async and graceful degradation, so collection failures never affect the main flow; second, data masking, where code snippets and secrets must be truncated or masked on the client side; third, storage tiering, with hot data used for real-time investigation and cold data archived to object storage to meet long retention and compliance requirements.

    Closing

    The bottleneck for scaling agents is shifting from model capability to engineering observability. When the execution process is reconstructed as a structured call chain, so that latency, tokens, and failures all map to a specific session, step, and tool call, a team finally has a basis for continuous optimization. If you already use general-purpose capabilities such as a cloud platform’s log service, monitoring and alerting, and object storage, they can serve as the foundation for storing and querying collected data; Baidu AI Cloud likewise provides standard product categories in this general observability space, making it easy for teams to combine them as needed and build their own full-picture agent observability solution.