Beyond Git Worktree

Token and Compute Cost Attribution Across Parallel Agent Runs

Tagging, tracing, and gateway limits tie parallel agent spend to its source.

· 9 min read
Cover illustration for “Token and Compute Cost Attribution Across Parallel Agent Runs”
Agent Cost Controls · November 27, 2026 · 9 min read · 1,959 words

Parallel coding agents need both a monthly API-key cap and a shared, run-scoped budget that is checked before every model or tool call. Token and compute cost attribution depends on request-time tags, nested traces, and isolated execution that connect each charge to a person, task, or trigger. Limits at each layer and graduated controls can cut context or reroute work before refusing more calls, while a gateway acts as the backstop that enforces the limits on each request.

Why parallel agent runs break the cost attribution model teams already have

A team runs five parallel agents on a refactor task. When the monthly bill arrives, nobody can identify which run caused the spike. Each agent kept its own context window, but the provider charged every call to an API key without knowing which task it was for. The invoice identifies the payer.

The familiar model of one key and one line item cannot explain a user action that spawns five agents reading the same files. Costs grow with loop depth and fan-out breadth across coordinators and workers, beyond any one prompt or agent type. A parent can launch children whose charges never enter its own ledger. Meanwhile, tools invoked by several branches appear as unrelated requests, and model changes within a session undermine session-wide pricing. The accounting boundary no longer matches the unit of work.

What the token ledger misses when agents run in parallel

Shared context reloads are the first failure mode. When five agents load the same utility module, the ledger lists five token charges without showing that they serve the same purpose. Those are real reads, but assigning them to whichever repository was active at inference time misstates who incurred the cost. The logical task required the repeated context. Cache accounting adds another distinction because cached-read, cached-write, and batch tokens have different prices, while allocating a cache write requires choosing between the project that triggered it and the one that first benefited.

Request-only accounting is the second failure mode. A gateway’s view is limited to individual completion calls. If a run crosses keys, providers, or processes, the gateway cannot infer that relationship. Child-agent charges can therefore disappear from the parent’s accounting even when every request has been logged. More rows do not create a run ledger.

Fragmented provider billing is the third failure mode. A workflow that uses Anthropic for reasoning, another provider for a separate step, and Snowflake Cortex for retrieval produces charges in three billing systems. Snowflake’s CORTEX_AI_FUNCTIONS_USAGE_HISTORY view became generally available on March 2, 2026, but Cortex usage records alone do not link agents that run in different processes.

Pricing an entire session at its primary model’s rate overstates costs when cheaper models handle file reads and a more capable model handles synthesis. Total tokens are not a sufficient pricing input. Claude Code’s local-first records illustrate the needed granularity through separate cache creation, cache read, input, and output tokens, with model identifiers per entry.

What variance across runs means for any budget set before execution

The same task can produce very different token totals without a corresponding difference in output quality. Agents make different tool-calling decisions, which change how much context accumulates and how often a loop repeats. A pre-run estimate therefore describes an expectation. Parallel fan-out adds to that uncertainty because several branches draw from the same budget, and each can vary on its own.

Uber’s disclosed consumption of its annual AI budget in four months illustrates the scale of the exposure. The architecture therefore requires immediate enforcement. A monthly cap is an outer fail-safe rather than a substitute for checking the next action. Without a shared counter that every branch can see, each agent can stay within its local allowance while the whole run costs more than intended.

The tagging schema that makes a parallel run traceable end to end

Request-time tagging begins at the SDK call site, before a proxy or gateway receives the call. The minimum schema includes user_id, agent_run_id, parent_run_id, feature or pipeline step, the model identifier for that call, and cost center or repository. These fields establish ownership before execution begins. In particular, parent_run_id connects spawned agents to their parent. The Anthropic SDK’s extra_headers pattern illustrates how attribution metadata can accompany a request without becoming a separate, retrospective logging exercise.

The schema serves two different queries. Low-cardinality fields such as feature, deployment environment, and prompt version support dashboards and threshold alerts. High-cardinality identifiers locate the individual user, run, and branch responsible for a spike. Gateway validation then makes these fields an admission requirement. TrueFoundry’s agentic CI/CD platform illustrates mandatory project, team, pipeline-step, and cost-center tags, with untagged requests rejected.

Not every charge has a single owner. Direct attribution works when an inference call clearly belongs to one task or project, while shared-context overhead has to be split through proportional allocation. Measurable allocation bases include lines of context drawn from each repository, tool calls per project, or output tokens written to each codebase. A hybrid ledger preserves both distinctions. It records the actual charge once, then assigns shared costs according to an explicit allocation rule independent of whichever agent happened to be active.

Where in the stack to capture cost: gateways, tracing platforms, and what each layer can and cannot do

Gateways sit between application code and model providers, where they can control calls as they pass through. LiteLLM, Portkey, Helicone, and OpenRouter occupy this layer, where requests can be counted, priced, routed, and subjected to budgets. They see only separate requests unless the caller supplies run identifiers. Portkey and Helicone depend on those headers to organize per-request costs into runs. OpenRouter is a hosted model marketplace and API gateway, rather than a self-hosted gateway, and its billing view does not itself supply the agent’s execution structure.

Tracing platforms answer a different set of questions. Laminar, Langfuse, LangSmith, and Datadog connect calls to the execution that produced them. Laminar is open-source and built natively on an observability framework, with costs rolling up from LLM spans into traces across tools, sub-agents, and providers. Langfuse and LangSmith provide trace, session, and user scoping, but their out-of-band observation does not refuse a call before execution. Datadog supplies run-level cost aggregation within its broader APM surface.

Anthropic’s Enterprise Analytics API, launched February 2026, provides named-user consumption and individual token and cost data, but lacks per-request granularity and has about a one-day delay for engagement data. It also requires enterprise-tier access. Snowflake’s usage view exposes Cortex consumption across dimensions including function, model, user, role, warehouse, and query. Neither view replaces live, run-scoped accounting.

The recommended setup pairs tracing with a gateway. Tracing supplies the nested, provider-spanning explanation of what a run cost and which branch incurred it. The gateway supplies request refusal and centralized routing. Selection therefore depends on how well a tool shows run structure and token detail for attribution, and how it enforces a budget in the path of a call for control. Seeing spending does not stop it unless calls can be refused, and refusal needs run identity to reliably stop the task that caused the spending.

How to stop AI coding agents from overspending mid-session

Production enforcement needs all three nested tiers. The innermost per-iteration limit caps tokens within a reasoning step and contains one bad retry. The middle per-run budget caps the whole execution through a counter shared by every branch. The outer monthly cap for each key or team catches spending that gets past the inner controls.

Every sub-agent must check the same run budget. Counting only local spending creates independent allowances that leave the combined execution unbounded. Propagating a run identifier through keys, providers, processes, and queues makes each call accountable to that shared ledger. TokenOps prepares policy decisions out of band and enforces them inside wrapped model-client and tool methods. The wrapper reads the decision before each call so it can stop the call before more work begins.

Graduated controls make this more useful than abrupt refusal alone. Policy can allow a call, shrink its context or model tier, reroute it to a cheaper model, or refuse it. Starting with the cheapest model plausibly capable of a task and escalating on low-confidence responses reduces expected spending. A fleet with one Opus orchestrator, three Sonnet workers, and one Haiku costs about 40 percent less than five Opus agents.

Soft alerts give teams time to act before a call is refused. Low-cardinality feature, deployment, and pipeline-step tags support meaningful signals such as spending reaching 2× its baseline. The graceful part of the wind-down is the opportunity to reduce or redirect work before the hard stop. Refusing the next call is nevertheless distinct from a complete graceful shutdown of the surrounding agent process. Budget enforcement should not be presented as a broader shutdown guarantee that the control layer does not establish.

Running agents in isolated sandboxes as the infrastructure prerequisite for attribution

The ledger is trustworthy only if execution respects its ownership boundaries. Each session needs isolated credential scope, network access, and token consumption so that concurrent agents cannot blur attribution through shared state. Fresh session credentials, revoked when execution ends, reduce ambiguity and the reach of a compromised key. Credentials kept from one run to the next weaken that boundary.

E2B provides cloud sandboxes built on Firecracker microVMs, with each sandbox running its own kernel and isolated from other sandboxes. Modal supports concurrent secure sandboxes using VM and gVisor isolation. Ramp uses Modal Sandboxes for background coding agents that write commits or pull requests, while Imbue runs hundreds of isolated coding agents in parallel on Modal. These examples establish the execution boundary at production scale. They do not replace the shared budget counter or request-level policy enforcement.

Claude Code uses Bubblewrap for Linux sandboxing and the Seatbelt framework on macOS. Sandboxing is enabled through /sandbox or the sandbox.enabled setting, so tags alone are not evidence that an execution boundary is active. Deployment location also introduces trade-offs. Managed sandboxes involve a third-party processor, network round-trips, and per-execution pricing, while self-hosted or bring-your-own-cloud approaches provide in-VPC residency, local-network latency, and infrastructure-based pricing. These choices shape the operational boundary within which attribution must work.

Agents-as-code extends that boundary to configuration. YAML or configuration files checked into the repository define tools, requested credentials, and budgets under reviewable version control. Prompts, retrieval sources, and policies can then be rolled back with the agent definition. A cost spike becomes traceable to a configuration version as well as a run identifier.

The governance model that makes parallel agent cost attribution sustainable at team scale

A sustainable model makes cost policy a team-owned artifact. Per-run caps, model assignments, and credential scopes belong in repository configuration subject to review before production use. The reviewer approving a change becomes part of its audit trail. Budget policy must also apply at session start, before invoice review. Otherwise, versioned configuration records what should happen without controlling what runs.

Organizational controls add scopes beyond the technical enforcement tiers. Per-session budgets bound individual work, per-developer or per-team controls expose disproportionate consumers, and time-period caps protect shared allocations. These scopes answer different ownership questions. They allow engineering and finance to distinguish an expensive task from a team-wide pattern without discarding the individual calls beneath either total.

The audit trail must include tool calls, model switches, cache reads, sub-agent spawns, and resulting diffs. That detail supports both cost analysis and compliance work, but attribution tags alone should not be equated with complete regulatory compliance. The EU AI Act’s Article 12 specifies logging relevant to risk identification, post-market monitoring, and operation. Cost records can contribute to that evidence without defining its full scope. For engineering leadership, the same records provide the chain needed to assess value, connecting a charge to a run, the run to a task, and the task to a business outcome.

Sources

  1. TokenOps: Real-time, run-scoped cost control for AI agents

More in Agent Cost Controls