Scaling AI Agents: Time, Cost, and Failure Diagnosis
Once coding agents move from a single working task to hundreds of parallel jobs, the engineering problem shifts from watching terminal output to measuring time structure, attributing token cost, and reconstructing failures. This article explains a runtime-generated trace model, plugin-based collection, layered timing and cost analysis, and the platform capabilities needed to diagnose agent runs at scale.
1. At Scale, the Questions Change
Getting one agent task to succeed and running hundreds of tasks in parallel for a week are two different engineering problems. The first only requires watching output scroll in a terminal. The second has to answer three quantitative questions:
- Time structure: Of a task’s total duration, how much is model inference, how much is tool execution, and how much is framework scheduling?
- Cost distribution: Which sessions, task types, and models consume the tokens? Is context growth causing repeated charges?
- Failure location: At which step did a failure or interruption occur, what were the inputs and outputs, and can the run be reconstructed afterward?
Most open-source coding-agent frameworks ship with trajectory views, session event logs, and tool-call lookup. Those features are local, single-session, and real time. They work well on a development machine, but they were not designed to review a batch of tasks, inspect a cost curve over time, or reconstruct a failure from three days ago on another machine. The missing piece is not raw data. It is structured trace data that spans sessions and machines and can be retained for the long term.
2. Understand the Runtime Before You Instrument It
A typical coding-agent framework lets a large model complete a full task inside a controlled sandbox: read and write files, run commands, call external services, and decide the next step from each result.
Architecturally, the common shape is a microkernel plus plugins. The kernel loads plugins according to a profile and manages their lifecycle. Model adapters, tool sets, sandbox policies, and session persistence are pluggable. CLI, interactive terminal, and headless modes share the same kernel. That matters for observability: instrumentation should attach at the same layer as a plugin, not by changing the kernel.
Execution alternates between reasoning and action, often called the ReAct pattern. One user task is a turn. Each round inside a turn—“reason, call a tool, observe the result”—is a step. The number of rounds and which tools are called are decided at runtime, so the execution structure cannot be known before the run starts.
That implies three constraints: parent-child relationships must be created dynamically at runtime; collection must cover both model calls and tool calls, the two kinds of leaves; and any monitoring design that depends on a static call graph does not apply.
3. Data Model: Five Entities for All Analysis
Do not start by piling on metrics. Define entities and relationships first. Five entities are enough:
| Entity | Meaning | Key fields |
|---|---|---|
| Session | One session or working-directory context | session_id, repository identifier, start time, profile |
| Turn | One user task | turn_id, goal summary, final status |
| Step | One reasoning-action round | step_index, decision summary |
| ModelCall | One model request | model name, input/output tokens, time to first token, total duration |
| ToolCall | One tool execution | tool name, argument summary, exit code, output bytes, duration |
A shared trace_id ties the trace together, and parent_id expresses parent-child links. An illustrative event:
{"trace_id": "t-7f3a91","session_id": "s-20240612-03","turn_id": "turn-02","step_index": 4,"span_kind": "tool_call","name": "shell.exec","start_ts": 1730000000123,"duration_ms": 842,"status": "ok","attributes": {"tool.exit_code": 0,"tool.output_bytes": 4120,"sandbox.policy": "restricted"}}
Two rules: keep large fields out of the trace (full file contents and complete command output belong in object storage; the trace stores only a reference and a summary); keep labels low-cardinality (do not put file names or user IDs into labels, or aggregation will explode).
4. Collection: Plug It In, Do Not Invade the Kernel
class AgentObservabilityPlugin:def on_session_start(self, ctx): ... # create trace_id, report sessiondef on_turn_start(self, ctx, goal): ... # open turn spandef on_step_start(self, ctx, idx): ... # open step spandef on_model_call(self, req, resp): ... # record tokens and latencydef on_tool_call(self, name, args, out): ... # record tool duration and statusdef on_turn_end(self, ctx, status): ... # close the turn and persist final status
Four engineering requirements follow. Export must use async batches and a bounded queue; when the queue is full, drop data rather than block the task. If the process crashes, a local buffer file should hold events for later replay. Sensitive data—secrets, internal addresses, and source snippets—must be redacted at collection time. All nodes need clock synchronization; otherwise cross-machine waterfall charts can show negative durations.
5. Time: Split It into Layers Before You Act
Total duration is the least useful metric. Aggregate by turn, then break the time down:
- Queueing and assembly: plugin load, sandbox creation, and context construction.
- Model inference: split further into time to first token (TTFT) and generation rate, to tell queue delay from long output.
- Tool execution: commands, builds, tests, and network calls—usually the source of the long tail.
- Framework overhead: serialization, event persistence, and policy checks.
A typical finding is that short tasks are bottlenecked by TTFT, while long tasks are bottlenecked by tool execution and context length. Layered data makes the next move clear: use a faster model path, parallelize tests, or trim tool output.
6. Cost: Attribute Tokens by Session and Model
The minimum loop for cost analysis is to record, on every model call, the model name, input tokens, output tokens, and cache-hit status, then aggregate upward:
SELECT model_name,sum(input_tokens) AS in_tok,sum(output_tokens) AS out_tok,count(*) AS calls,avg(duration_ms) AS avg_msFROM agent_spanWHERE span_kind = 'model_call'AND ts BETWEEN :from AND :toGROUP BY model_nameORDER BY out_tok DESC;
Two views are more useful than a single total. First, plot input tokens against step within a turn. A steep rise means history and tool output were not trimmed—the most common hidden cost. Second, compare cost per task by task type, which shows whether a class of work is a good fit for an agent.
7. Failures and Interruptions: Classify, Then Reconstruct
Collapse status into a finite set so it can be counted: invalid model output, non-zero tool exit, timeout, context limit exceeded, external dependency unavailable, human interruption, and process crash. Each class calls for a different response.
Reconstruction depends on an event stream plus snapshots at key points. On failure, write the message history and summaries of tool arguments and outputs to object storage, and keep only a pointer in the trace. Even if the original session has been cleaned up, the decision path can be replayed on the platform by trace_id. Replay is for locating the failure. It is not a deterministic reproduction—model output is stochastic.
8. On the Platform: Search, Aggregation, and Alerts
Collected data is useful only with platform capabilities: trace search (combined filters on session, status, model, and duration range), aggregation (multi-dimensional drill-down of time and cost), and dashboards with alerts (for example, tokens per task over a threshold, a sudden rise in tool failure rate, or a rising P95 duration). Storage and query can reuse general cloud log services, monitoring and alerting, and object storage. Vendors such as Baidu AI Cloud offer this class of general-purpose products, so a full stack does not have to be built in-house.
9. Pitfalls
- High-cardinality labels make aggregation time out. This is usually the first wall.
- Synchronous export slows tasks. Collection must be able to degrade.
- One sampling policy for everything: capture failed traces in full and sample successful traces.
- Collecting model calls but not tool calls leaves half of the time attribution missing.
- Ignoring clock drift makes cross-machine data impossible to align.
- Leaving retention and redaction undecided makes later remediation very expensive.
Conclusion: Agent observability turns an execution structure that exists only at runtime into a structured trace that can be searched, aggregated, and retained. With a clear data model, non-invasive collection, drill-down for time and cost, and reconstructable failures, diagnosis at scale moves from guessing to looking it up.
