Observability for AI Agents at Scale: Tracing, Cost, and Failure Analysis
As AI agents move from validation into daily development workflows, the focus shifts from single-run correctness to latency attribution, cost distribution, and failure replay. This article examines why typical open-source coding agent frameworks, built on a microkernel with plugins and a runtime-generated ReAct loop, produce flat event streams that cannot answer engineering questions across sessions and machines. It presents a practical approach: a kernel-level collection plugin that translates events into structured traces using a unified task, turn, and span model, dual real-time and offline data paths, a three-step latency attribution method, consistent cost measurement dimensions, and first-class failure data. The result is a closed loop of alerting, trace investigation, and session review that applies to agent operations on cloud platforms as well.
1. Introduction: What Changes Once Agents Scale
AI agents are now part of everyday development workflows for many teams. During validation, users only care whether a single run produces the right result. As task volume, concurrency, and machine count grow together, attention naturally shifts to three more engineering-oriented questions:
- Latency attribution: Does a task spend its time on model inference, tool execution, sandbox startup, or network waits?
- Cost distribution: Which sessions, models, and task types concentrate token consumption, and is there any abnormal amplification?
- Failure replay: At which step did a failure or interruption occur, what were the context, parameters, and response at that moment, and can the process be fully reconstructed?
All three share one prerequisite: structured process data that spans sessions and machines and can be retained long term. The built-in observability of most coding agent frameworks is scoped to “local machine, single session, real time,” which cannot cover these needs. This article takes a typical open-source coding agent framework (command-line based, referred to below as a “coding agent framework”) as the analysis subject and discusses how to add engineering-grade observability on top of it. The same approach applies to operating and governing agent applications built on cloud platforms such as Baidu AI Cloud.
2. How Coding Agent Frameworks Run: Why Process Data Is Inherently Uncertain
Understanding the observability challenge requires understanding the execution model of these frameworks.
2.1 Microkernel with Full Plugin Architecture
These frameworks generally use a “microkernel + plugin” structure: the kernel only assembles plugins according to a configuration (profile) and manages their lifecycle. Model adapters, tool sets, sandbox policies, and session persistence are all pluggable plugins. The command line, terminal UI, and headless modes share the same kernel.
This design directly affects observability: observability should also be mounted as a plugin at the kernel layer, rather than scattered across individual tool implementations. Otherwise, adding a tool or replacing a model adapter will create gaps in instrumentation.
2.2 The ReAct Loop: Structure Is Unknown Before Runtime
The execution model is a reason-act-observe (ReAct) loop. One user task is a turn, and each round of “reason + call tool + observe result” within a turn is a step. The number of rounds and which tools get called are decided by the model at runtime.
This means the call structure is not determined at compile time but generated at runtime as a tree or graph. Traditional APM topology discovery, which relies on pre-declared service dependencies, fails here. The call graph must be reconstructed in real time from a runtime event stream.
The output of a turn can be abstracted into two data streams: a “trajectory view” for humans and an “event stream” for machines. The latter is what has real engineering value.
3. Inventory of Built-in Observability and Its Three Break Points
These frameworks typically provide three capabilities out of the box:
- Session trajectory view: A browser-based execution record table organized by turn, showing token usage and latency for individual records.
- Event stream persistence: The complete event stream is written to a local session directory as compressed JSONL, with no data loss.
- Tool call search: Call parameters and results are recorded in the event stream and support full-text search within a session.
This works well for single-machine debugging, but it is a flat, time-ordered event sequence that lacks three things. Once scale increases, these gaps quickly become three break points:
Break point 1: No call relationships, so latency cannot be attributed. The event stream tells you that tool A was called before tool B, but not whether A and B are nested or which is the parent. Without that, you cannot compute the share of model inference time, tool execution time, or queuing and sandbox cold-start time.
Break point 2: Data stays local and cannot be aggregated across sessions. When tasks are spread across dozens of machines and hundreds of sessions, the question “what does the cost distribution look like over this period” simply cannot be answered from local data.
Break point 3: The real-time view is not replayable. A failure from a few days ago may have had its local logs cleaned up or rotated. Without persistent data carrying trace identifiers, reproduction becomes guesswork.
4. The Fix: Reconstructing Structured Call Chains as a Plugin
The solution is not to replace the framework but to mount a collection plugin at the kernel plugin layer that translates the event stream into a structured call chain (trace).
4.1 A Unified Data Model
A four-layer model is recommended, with layers linked by consistent IDs:
| Layer | Meaning | Key fields |
|---|---|---|
| Task | Full lifecycle of one user request | task_id, status, total latency, total tokens |
| Turn/Step | Each round of the ReAct loop | step_id, parent_id, round index |
| LLM span | One model request | model name, input/output tokens, time to first token, total latency |
| Tool span | One tool execution | tool name, parameter digest, return code, latency, retried or not |
Session runs horizontally across these layers, linking multiple tasks from the same user.
4.2 Where to Instrument
- Model adapter plugin: capture token usage, streaming time to first token, and finish reason.
- Tool registry: wrap tool execution uniformly to capture parameter digests, return codes, and latency.
- Kernel loop: generate step boundaries and parent-child relationships.
- Session persistence plugin: inject session_id and trace_id to correlate across layers.
Illustrative code (pseudocode, showing only the wrapping idea):
def wrap_tool(tool):def invoke(ctx, params):span = tracer.start_span(name=f"tool:{tool.name}",parent=ctx.current_span,attrs={"tool.params_digest": digest(params)},)try:result = tool.run(ctx, params)span.set_status("ok")return resultexcept Exception as e:span.set_status("error", str(e))raisefinally:span.end() # record latency automaticallyreturn invoke
4.3 Data Plane: Offline and Real-Time Paths
- Real-time path: Events are reported with low latency to a logging service or message queue for online search and alerting.
- Offline path: Events are written in batches to object storage for aggregation and long-term retention.
Both paths share the same schema, avoiding “two sets of definitions.”
5. Querying Latency: From Total Duration to Share
With parent-child spans, latency becomes a decomposable tree instead of a single number. A three-step attribution method is recommended:
- Self time first: A span’s self time equals its total latency minus the sum of its child spans. The share of model inference versus tool execution follows directly.
- Sort within a level: Order spans under the same step by self time descending to quickly find the most expensive step.
- Compare against baselines: Compare the trace’s latency distribution with the P50/P95 baseline for the same task type to identify long tails.
Common findings include: serial tool execution inflating wall time, a single tool’s retries amplifying latency, overly long model output raising the inference share, and sandbox cold starts not being counted in tool latency. These conclusions can only be reproduced reliably on structured data.
6. Querying Cost: Align Definitions First, Then Optimize
Cost analysis is easiest to get wrong at the level of definitions. Three dimensions should be made explicit:
- Attribution dimensions: session, task, task type, model, tool.
- Measurement dimensions: input tokens, output tokens, cache-hit tokens, call count.
- Time dimension: aggregated hourly or daily to observe trends and spikes.
In practice, attach token fields to the model call span; aggregation queries can then answer which session is most expensive, which model contributes most of the cost, and which task type has rising unit cost. Further optimization can use general engineering measures such as context trimming, truncating tool results, and tiered model routing, but the effect must be validated with data rather than tuned by intuition.
7. Querying Failures: Making Interruptions Replayable
The key to locating failures is to treat failure as first-class data:
- Record the failure stage for each interruption (model call failure / tool execution failure / loop limit exceeded / user cancellation).
- Retain parameter digests and return codes at the time of failure, with sensitive data masked and summarized.
- Use trace_id to link “failure point—upstream input—downstream impact,” with one-click navigation to the corresponding session context.
- Configure alerting rules such as a spike in failure rate, an abnormal rise in average rounds, or per-task tokens exceeding a threshold.
Together with a dashboard, this forms a closed loop of “alert detection—trace investigation—session review,” shrinking what used to take hours of digging through local logs into minutes.
8. Rollout Plan and Pitfall Checklist
A four-step rollout is recommended:
- Unify IDs and schema: Define the task/turn/span model and field conventions first.
- Instrument via plugins: Wrap centrally at the kernel and tool registry instead of intruding into business tools.
- Dual-path data plane: Real time for alerting, offline for aggregation.
- Dashboards and alerts: Ship three core views first: latency share, cost distribution, and failure rate.
Pitfalls to avoid: do not instrument inside each tool separately, which fragments definitions; do not record full raw parameters, use digests and masking; do not keep only the real-time view, always persist to storage; do not ignore the headless mode, which is often the main source of batch tasks.
9. Conclusion
Observability for agents at scale is essentially about translating an execution structure that is only determined at runtime into structured data that can be aggregated and replayed. Hold on to three supports—a unified data model, plugin-based collection, and a dual-path data plane—and latency attribution, cost distribution, and failure replay move from “guessing based on experience” to “querying by data.” That is the key step in taking agents from usable to operable.
