Agent Observability at Scale: Latency, Cost, and Failure Diagnosis

    When coding agents move into daily development workflows, the focus shifts from "did it produce the right result" to three engineering questions: where latency is spent, where costs concentrate, and where failures occur. This article explains why answering these questions requires structured, cross-session, cross-machine trace data, how to design a collection layer that converts raw event streams into queryable call chains via a native plugin, and how to diagnose latency, cost, and failure issues in practice. It concludes with an implementation checklist covering field standardization, trace storage, aggregation, and alerting.

    Agent Observability at Scale: Latency, Cost, and Failure Diagnosis

    1. At Scale, the Question Is No Longer “Is the Result Correct?”

    Once coding agents enter daily development workflows, the early concern is usually whether a single task can be completed and whether the generated output is correct. But as task volume, concurrency, and machine counts grow, operators quickly shift their attention to three more engineering-oriented questions:

    1. Where is latency spent? Of the total time for a task, how much goes to model inference, tool execution, queueing, or retries and timeouts?
    2. Where do costs concentrate? Which sessions, models, and task types consume the most tokens? Are there wastes caused by long contexts, repetitive tool outputs, or ineffective loops?
    3. Where do failures happen? Do failures and interruptions occur during inference, tool calls, result parsing, or policy interception? Can an anomaly from days ago still be fully reconstructed?

    All three questions share one prerequisite: structured trace data that spans sessions and machines and can be retained long-term. A real-time, single-session view can only answer “what happened this one time”—it struggles to answer “how did a batch of tasks perform overall,” “how were costs distributed over a period,” or “how can a historical failure be reproduced.”

    2. The Execution Model Determines the Shape of Observability Data

    Typical coding agent frameworks use a plugin-based architecture: the kernel assembles plugins and manages their lifecycle, while model adapters, toolsets, sandbox policies, and session persistence are all pluggable modules. The GUI, terminal UI, and headless mode share the same kernel. The execution model is usually a “reason–act” loop: a user task is a turn, and each round of reasoning, tool invocation, and observation within a turn is a step. The number of loop iterations and which tools get called are decided by the model at runtime, so the execution structure cannot be fully determined in advance.

    Such frameworks typically ship with some out-of-the-box observability capabilities, for example:

    • Session trajectory view: execution records organized by turn, with token usage and duration visible per record;
    • Session event stream persisted to disk: the full event stream stored as compressed JSONL in a local session directory, with relatively complete data;
    • Tool call search: tool call parameters and results recorded in the event stream, with full-text search over sessions.

    These capabilities work well for local, single-session, real-time troubleshooting. But at scale, clear gaps remain: the event stream is time-ordered and lacks stable call relationships and per-stage time breakdowns; data lives on individual machines and is hard to aggregate across machines; long-term retention, cost attribution, historical failure replay, and alerting all require additional work.

    3. Collection Layer Design: Reconstructing Event Sequences into Call Chains

    To close these gaps without modifying agent business logic, a reasonable approach is to mount the collector as a native plugin that passively listens to execution events and converts the raw event stream into structured call chains. The design should follow several principles:

    1. Unified identifiers: assign stable IDs to tasks, sessions, turns, steps, model calls, and tool calls, and record parent-child relationships;
    2. Causal reconstruction: express the call chain with trace_id, span_id, and parent_span_id instead of relying on timestamp ordering alone;
    3. Normalized attributes: for model calls, record model category, input/output tokens, time to first token, total duration, retry count, and error code; for tool calls, record tool category, parameter summary, result summary, duration, and error type;
    4. Security and retention: sanitize parameters and results; store detailed traces, aggregated metrics, and search logs in separate tiers, with retention periods set according to compliance requirements.

    An illustrative event structure can be abstracted as follows:

    1. {
    2. "trace_id": "task-xxx",
    3. "session_id": "session-xxx",
    4. "turn_id": "turn-1",
    5. "span_id": "step-3-tool-1",
    6. "parent_span_id": "step-3",
    7. "span_type": "tool_call",
    8. "start_time": "2025-01-01T10:00:00Z",
    9. "duration_ms": 1200,
    10. "status": "error",
    11. "attributes": {
    12. "tool_category": "file_operation",
    13. "error_type": "timeout",
    14. "retry_count": 1
    15. }
    16. }

    With structured data like this, “time-ordered events” can be reconstructed into “queryable, aggregatable, drill-downable call chains.”

    4. Diagnostic Methods for the Three Problem Types

    4.1 Latency: Look at the Critical Path, Not Just Total Duration

    Break latency down into four categories first: model inference, tool execution, queueing, and retries/timeouts. Compute the critical path from the call chain, locate the slowest spans, and track P50, P95, and P99 separately. If time to first token is high, focus on the model and network sides. If tool execution dominates, examine tool types, parameter sizes, external dependencies, and timeout configurations. If retry counts are abnormal, check whether error classification and retry policies are inflating total duration.

    4.2 Cost: Aggregate by Session, Model, and Task Type

    Token cost should not be evaluated by total volume alone. Aggregate by session, model, task type, tenant, or project, and attribute cost using input/output ratios, context growth curves, and tool response sizes. Common sources of waste include repeatedly carrying long contexts, oversized tool results, ineffective loops, and duplicate calls. Set budget thresholds and anomaly alerts at the aggregation layer, while keeping drill-downable session traces at the detail layer.

    4.3 Failures: Classify First, Then Locate the Interruption Point

    Failures should be classified at minimum into model errors, tool errors, timeouts, policy rejections, sandbox exceptions, and result parsing failures. When diagnosing, first examine the failed span and its parent chain to confirm where execution was interrupted; then check whether retry chains masked the original error; finally, combine the event stream, configuration version, and tool result summaries into a reproducible snapshot. High-frequency failure patterns should be turned into alert rules and regression test cases.

    5. Implementation Checklist and Summary

    When implementing, start by unifying the field dictionary and identifier conventions, then build the collection plugin, trace storage, search and aggregation, and alerting dashboards. Within Baidu AI Cloud’s observability stack, the log service can carry detailed events, distributed tracing can carry call relationships, and metrics with alerting can carry aggregated views. In terms of sequencing, cover latency and failure diagnosis first, then fill in cost attribution; aggregate from single machines to cross-machine views first, then add long-term retention and historical replay. The ultimate goal is for every agent task to have an explainable latency structure, an attributable cost structure, and a traceable failure chain—providing the foundation for stable operation at scale.