Observability for AI Agents at Scale: A Guide to Debugging Latency and Cost

    As AI coding agents move from single-session debugging into production, teams need structured observability to answer three questions: where time is spent, where token cost concentrates, and where failures occur. This guide explains the ReAct execution model of plugin-based open-source coding agents, why their built-in session traces are insufficient at scale, how to define a four-layer span model (turn, step, model call, tool call), and how to collect trace data through native plugins. It also covers practical methods for latency, cost, and failure investigations, plus platform-side storage and alerting recommendations.

    1. Why Problems Change at Scale

    AI agents are now part of everyday development workflows for many teams. Once usage scales up, consumers care about more than whether a single result is correct. Three additional concerns appear:

    • Latency breakdown: whether time goes to model inference or tool execution;
    • Cost distribution: which sessions and models consume the most tokens;
    • Failure localization: which step a failure or interruption occurred in, and whether the process can be replayed.

    These questions are rarely a blocker during single-machine, single-session, real-time debugging, because developers can simply watch the terminal. Once concurrency rises, execution nodes grow from one machine to dozens, and an anomaly from several days ago needs to be reviewed, the “watch the screen” approach breaks down. This article uses a mainstream category of open-source coding agent frameworks (CLI-based, with a microkernel and fully pluginized architecture) as its technical background, and discusses how to add structured trace data on top of them to build observability that can be retained long term and aggregated for analysis. No specific vendor products are involved, and all capability descriptions are limited to general industry categories.

    2. How These Coding Agents Work

    The purpose of these frameworks is to let a large model autonomously complete a full task in a controlled environment: reading and writing files, executing commands, calling external services, and deciding the next action based on each result.

    Organization typically follows a microkernel plus fully pluginized design. The kernel only assembles plugins by profile and manages their lifecycle. Model adapters, tool sets, sandbox policies, and session persistence are all pluggable plugins, and the CLI, terminal UI, and headless modes share the same kernel. Observability is mounted at this same layer, which is the root reason it can be integrated non-invasively.

    The execution model is a ReAct loop. One user task is called a turn, and each round of inference, tool call, and observation inside a turn is called a step. The key constraint is that the number of loop rounds and which tools get called are decided by the model at runtime, so the execution structure cannot be known before the run. This directly means the observability approach cannot rely on a predefined fixed call-chain template; it must be reconstructed from the event stream after the fact.

    A turn usually produces two outputs: a human-facing display view and a machine-facing event stream.

    2.1 What the Framework Provides Out of the Box

    Based on the event stream and persisted data, these frameworks generally offer three built-in capabilities:

    1. Session traces: an execution record table organized by turn in the browser, where you can inspect token usage and latency for individual records;
    2. Session event stream persistence: the complete event stream is stored locally in the session directory as compressed JSONL, with no data loss;
    3. Tool call search: tool call arguments and results are recorded in the event stream and support full-text search within a session.

    These three capabilities are very effective for debugging a single session. The problem is their scope: local machine, single session, real time.

    2.2 Why Call Relationships Must Be Reconstructed

    Process data is essentially a time-ordered sequence of events, lacking explicit parent-child call relationships and per-span time accounting. On a single machine, developers can manually infer relationships from adjacent timestamps. After scaling out, however, more machines and interleaved concurrent sessions make manual inference cost more than it returns. The gaps fall into four categories:

    • No cross-session aggregation: cannot answer “which model consumed the most tokens over the past 7 days”;
    • No cross-machine retention: local files are lost when containers are destroyed, so data cannot be retained or searched long term;
    • No call relationships: latency cannot be attributed to the three segments of inference, tool, and queueing;
    • No failure context: events before and after an interruption point are hard to pull together in one trace.

    3. Structured Trace Model: Define Before Collecting

    The first step is not choosing a tool but defining the data model. At minimum, abstract four layers of entities:

    Layer Entity Key Fields
    L1 Task (turn) Task ID, session ID, status, total latency, total tokens
    L2 Inference round (step) Step index, input/output tokens, model name, latency
    L3 Model call Time to first token, generation time, retry count, error code
    L4 Tool call Tool name, argument summary, execution time, return status

    With this table, “is time spent on inference or tools” becomes a sum-and-compare of L3/L4 durations; “which sessions concentrate cost” becomes an aggregation grouped by L1 and then by model name; “which step failed” becomes filtering by the status field and walking back to the parent step and adjacent events.

    An illustrative instrumentation structure (pseudocode, expressing field semantics only):

    1. span(kind="tool", name="shell.exec",
    2. attrs={"exit_code": rc, "duration_ms": cost},
    3. parent=current_step_span)

    The key point: parent-child relationships must be determined on the collection side, not guessed afterward from timestamps.

    4. Collection Approach: Mount as a Native Plugin

    Because the kernel is fully pluginized, the recommended approach is to integrate collection logic as a native plugin rather than wrapping the CLI or parsing terminal output. There are three reasons:

    1. Plugins live inside the lifecycle and can access real turn/step boundaries and tool call context;
    2. No framework source code is modified, so upgrades stay easy;
    3. All three UI modes share the kernel, so one plugin integration covers everything.

    A few practices are recommended on the collection side:

    • Asynchronous batch reporting, with local buffering and retry on failure, so observability does not slow the main flow;
    • Large field truncation: keep only summaries and lengths for file contents and command output to prevent trace data from ballooning;
    • Sensitive data redaction: credentials and tokens in arguments are handled on the collection side;
    • A unified Trace ID across a turn, ensuring correlation across plugins and processes.

    5. From Data to Answers: Investigating Three Problem Types

    5.1 Latency Investigation

    Start with total turn latency, then split it into inference and tool segments. If the tool segment dominates, check for serialized execution, repeated commands, and missing caching. If the inference segment dominates with high time to first token, look at context length and model-side queueing.

    5.2 Cost Investigation

    Aggregate across the two dimensions of session and model to locate anomalous sessions, then drill down to the step level to identify two typical wastes: repeated retries and repeatedly carrying the full context.

    5.3 Failure Investigation

    Filter failed and interrupted records by the status field, pull context along parent-child relationships, and distinguish whether the cause is a non-zero tool return, a sandbox policy block, or a model-side timeout. Long-term retention of structured data makes “a failure from several days ago” reproducible.

    6. Platform Capabilities and Adoption Recommendations

    Collected trace data needs to land on a foundation that is searchable, aggregatable, and alertable. Common industry practices include: a trace search service that filters by Trace ID and attributes; a logging service that retains raw events long term; and monitoring and alerting that provide threshold dashboards for latency and failure rate. Baidu AI Cloud can provide general-purpose logging, monitoring and alerting, and container platform capabilities as the underlying foundation in these scenarios.

    A three-step adoption path is recommended: first, validate on a single node that the plugin does not alter the main flow and that fields are complete; then scale to multiple nodes, verifying Trace ID continuity and data retention periods; finally, configure dashboards and alerts to turn “investigate after the fact” into “prevent before it happens”.