Observability and Cost Governance for AI Agents at Scale: Troubleshooting Practices

    This article explains how to build cross-session, cross-machine observability for AI coding agents as they move from pilots to production. It covers the agent execution model, a four-layer design based on native plugin collection and structured traces, and how to use turn/step traces for latency attribution, cost attribution, and failure replay. It also includes a practical rollout checklist and common pitfalls to avoid.

    1. Why Observability Changes at Scale

    AI agents have become part of daily development workflows for many teams. During a pilot, evaluation usually comes down to a single question: did the task produce the correct result? But as concurrent tasks, user counts, and connected repositories all grow, both users and platform teams naturally shift their attention to three more engineering-focused questions:

    1. Latency attribution: Where does a task actually spend its time—model inference or tool execution such as compilation, testing, retrieval, and external API calls?
    2. Cost attribution: Which sessions, models, and task types concentrate token consumption, and is there any abnormal amplification?
    3. Failure replay: At which step did a failure or interruption occur, what were the context, parameters, and response at that moment, and can the full process be reconstructed?

    These three questions share a common trait: none of them is a “single-session” problem. They are aggregate questions across a batch of tasks, a period of time, and multiple machines. Yet the built-in observability of most open-source coding agent frameworks is scoped to exactly the opposite: local, single-session, and real-time.

    Take a common coding agent framework in the industry (referred to below as the “coding agent framework”) as an example. It typically ships with three out-of-the-box observability capabilities: an in-browser session trace view organized by turn, where you can inspect token usage and latency for a single record; a complete event stream persisted losslessly as compressed JSONL in a local session directory; and tool-call retrieval based on the full session text. These capabilities are very effective for “tuning how this current run behaves,” but the moment you want to answer “how did that failure last Wednesday actually happen,” you immediately hit three walls:

    • Data is scattered across multiple dev machines and containers, with no unified entry point;
    • The persisted format is a machine-oriented append-only log stream, not a query-oriented structured model;
    • There is no aggregation by time or task dimension, making trend and distribution analysis impossible.

    So the prerequisite for scaling is not switching frameworks, but adding a layer of structured trace data that spans sessions and machines and can be retained long term.

    2. General Runtime Model: Why You Must Understand It First

    Good observability starts with understanding the execution structure of the observed object. The mainstream coding agent frameworks share three common traits.

    Microkernel plus full plugin architecture. The kernel only assembles plugins according to a configuration (profile) and manages their lifecycle. Model adapters, tool sets, sandbox policies, session persistence, and interface form (CLI / terminal UI / headless) are all pluggable. This design is very friendly to observability: observability itself is just a plugin, and attaching it at the kernel layer leaves upper-layer interfaces unaffected.

    ReAct-style loop. A user task is called a turn, and each round of “reason—call tool—observe result” within a turn is called a step. The key point 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 determined before the run. This directly dictates that the observability data model must be a “tree/chain” rather than “fixed stages.”

    Two data outputs. One is a real-time view for humans; the other is a persisted event stream for machines. What is truly valuable in engineering is the latter, because it is lossless and replayable.

    From this, four hard requirements for an observability solution follow:

    • It must express the parent-child relationship between turns and steps (tree expansion);
    • It must express the latency, tokens, parameters, and responses of a single model call and a single tool call;
    • It must associate session IDs with tasks, repositories, and execution environments;
    • It must support aggregate retrieval by time range and attribute dimensions.

    3. Overall Design: Native Plugin Collection Plus Structured Traces

    The recommended implementation is to attach a collector as a native plugin on the coding agent framework, reconstruct the execution process into a structured call chain, and let the platform side handle storage, retrieval, aggregation, and alerting. The whole design has four layers.

    1. Collection layer: The plugin subscribes to kernel events (session start/end, reasoning round start/end, tool call start/end, errors and interruptions) and enriches context attributes when events fire.
    2. Reporting layer: Batch, asynchronous, compressible reporting, with local buffering and retry on failure, to avoid blocking the main flow.
    3. Storage and indexing layer: Store data using a trace–span model and build indexes on session ID, task ID, model name, tool name, status code, and so on.
    4. Analysis and consumption layer: Trace retrieval, aggregate dashboards, alerting rules, and cost-oriented grouped statistics.

    A skeletal plugin example (pseudocode, expressing only mount points and fields, not bound to any specific API):

    1. class ObservabilityPlugin:
    2. def on_turn_start(self, ctx):
    3. self.trace = ctx.new_trace(
    4. session_id=ctx.session_id,
    5. task_id=ctx.task_id,
    6. repo=ctx.repo,
    7. env=ctx.env_profile,
    8. )
    9. def on_step_start(self, ctx):
    10. self.step = self.trace.start_span(
    11. name="step", turn=ctx.turn_index, step=ctx.step_index
    12. )
    13. def on_model_call(self, ctx):
    14. span = self.step.start_span("model.call")
    15. span.attrs.update(model=ctx.model, prompt_tokens=ctx.usage.input,
    16. completion_tokens=ctx.usage.output)
    17. ctx.on_done(lambda: span.end(status=ctx.status))
    18. def on_tool_call(self, ctx):
    19. span = self.step.start_span("tool.call")
    20. span.attrs.update(tool=ctx.tool_name, args_digest=ctx.args_digest)
    21. ctx.on_done(lambda: span.end(status=ctx.status,
    22. result_digest=ctx.result_digest))

    Note the compliance and engineering details: tool arguments and responses may contain sensitive information, so the collection side should support digesting, length truncation, and field masking, reporting only digests and status by default while keeping the original text local.

    4. Querying and Interpreting the Three Core Scenarios

    Scenario 1: Latency attribution. With the turn/step tree, latency is automatically layered. The interpretation method is to first look at total turn latency, then at the share of model.call versus tool.call inside a step. In practice, tool execution in coding tasks (dependency installation, compilation, testing) is often an underestimated major cost; if tool.call consistently accounts for more than inference, the optimization focus should be on caching, parallelism, and tool timeout settings rather than switching to a faster model.

    Scenario 2: Cost attribution. Group and sum tokens by the three dimensions session_id, model, and task_id to quickly answer “where is the money going.” Common anomaly patterns include: an abnormally high number of steps in a single session (the model stuck in a loop), context repeatedly carried in full (history not trimmed), and small tasks mistakenly using large-parameter models. Plotting step count against tokens as a scatter comparison usually makes anomalies obvious at a glance.

    Scenario 3: Failure replay. In a trace, a failure appears as an error status on a span. Because the event stream is lossless, replay can trace upward from the failed span to the full turn context and downward to the tool’s actual parameters and response. Interruptions (timeouts, manual termination, killed processes) should be modeled separately from business errors, otherwise alert noise will be very high.

    5. Rollout Steps and Pitfall Checklist

    1. Unify identifiers first: Inject a stable session ID and task ID for every task; otherwise all subsequent aggregation is impossible.
    2. Unify clocks next: For multi-machine deployments, ensure time synchronization; otherwise the causal order of cross-machine traces will be scrambled.
    3. Combine sampling with full collection: Collect metadata in full by default, and sample large parameter payloads by policy to control storage and bandwidth.
    4. Tier retention: Use hot data for near-real-time troubleshooting and archive cold data to object storage, balancing cost and traceability period.
    5. Make alerts actionable: Alerts should bind “explainable metrics plus jump links,” such as step count exceeding a threshold, rising tool failure rate, or a single session’s tokens exceeding budget.
    6. Avoid collection backfire: Reporting must be asynchronous, degradable, and toggleable; a plugin exception must never affect the success of the main task.

    6. Conclusion

    Governance of agents at the scaling stage is essentially about turning a “non-deterministic runtime execution structure” into “queryable structured data.” Attaching collection as a native plugin, expressing turns and steps with a trace model, and supporting latency and cost attribution with multi-dimensional aggregation is a reusable general path in the industry. In related practices at Baidu AI Cloud, such capabilities are typically implemented by combining general product categories such as log services, monitoring and alerting, and object storage. Teams can build or select on this basis, and by first getting identifiers, clocks, and masking solid, subsequent troubleshooting and cost optimization will follow naturally.