How should an instance attribute token cost across an OTel span tree when a single LLM call is re-emitted by a retry, a fan-out, and a memory-write side effect — and what breaks when it does

**Date of Record:** 2026 December 2 **Scope:** Applies to OpenTelemetry-instrumented agent runtimes where LLM calls, tool invocations, and memory operations emit spans with `gen_ai.usage.*` (or equivalent token counters) and where a cost attributor reconciles those spans into per-agent, per-tool, and per-memory-operation ledgers. Does not apply to single-shot inference with no retries, no fan-out, and no downstream memory writes.

Core Distinction

There are two distinct quantities that OTel-based GenAI observability conflates under the label "cost": **emitted token usage** (what the provider billed for a given request attempt) and **attributed token usage** (what the ledger assigns to a logical agent/tool/memory node). In a clean trace these are equal. The boundary failure is that they are *not* equal whenever a span is **re-emitted** — retried after a transient 429/5xx, replayed by a fan-out supervisor, or re-triggered as a side effect of a memory write that itself calls an LLM (e.g., episodic-to-semantic distillation). The attributor sees N child spans with token counters and must decide whether they represent N billable events or 1 logical operation with N-1 wasted attempts. Getting this wrong is not a rounding error: it silently doubles or triples the per-agent cost ledger and misroutes blame to the wrong tool or memory node.

The invariant that must hold: **every billable token counter appears exactly once in the ledger, attached to the logical node that *caused* the spend, not the node that *observed* it.** Retries, fan-out siblings, and memory-write sub-calls all violate this invariant unless the trace carries explicit causality metadata that the attributor is required to honor.

What Was Observed

A three-agent pipeline (planner → executor → auditor) with a retrieval memory tool and a post-task distillation step. Each LLM call emitted a span with `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and a `gen_ai.request.attempt` attribute set by the SDK's retry middleware. The attributor walked the span tree and summed `usage.*` per `agent.id` and per `tool.name`.

During a provider incident, the executor's tool-call loop hit 429s. The SDK retried each LLM call up to 4 times. The trace showed, for one logical executor step:

The attributor summed all 4 retry spans plus the distillation span into `agent.id=executor`. Result: the executor's ledger showed **5× the actual billable input tokens** for that step. The auditor, which had no retries, looked cheap by comparison. A budget alert fired on the executor and triggered a circuit breaker that disabled the tool loop — a false positive caused entirely by attribution, not by spend.

A second, subtler case: the fan-out supervisor re-emitted the *same* `agent.step` span payload to two executor replicas for hedging. Both replicas succeeded; both emitted full usage. The attributor counted both. Only one was actually billed (the loser was cancelled server-side and the provider refunded it), but the trace had no `gen_ai.response.finish_reason=cancelled` marker on the loser because the cancellation arrived after the span closed.

Condition of Validity

Attribution is only correct under the following conjunction, and any single violation produces ledger drift:

  1. **Attempt deduplication.** Every retry span is a child of a single logical-operation span, and the logical span carries a stable `logical.op.id`. The attributor must sum usage across attempts *only if* the provider bills per attempt (it usually does for input tokens on 429 because the prompt was tokenized), and must *not* sum if the retry was a client-side pre-flight abort that never reached the provider. The trace cannot distinguish these without a `gen_ai.request.billed` boolean set by the transport layer. Absent that flag, the attributor's default (sum all attempts) overcounts pre-flight aborts and undercounts nothing — an asymmetric, silent bias.
  1. **Fan-out causal ownership.** In a hedged fan-out, exactly one sibling is the "owner" of the logical operation. The owner is determined by first-`finish_reason`-success, not by span start order or trace ID ordering. The attributor must attribute the operation's cost to the owner and mark losers as `cancelled` with zero attributed cost. This requires the supervisor to emit a `fanout.owner.span_id` link on the parent — a forward reference that is only resolvable after all siblings close, which means the attributor cannot be a streaming reducer; it must be a batch reconciler over the closed trace.
  1. **Memory-write side-effect separation.** A memory write (distillation, summarization, embedding) that internally calls an LLM must emit its usage under the *memory operation's* node, not the calling agent's node. The invariant is: the node that pays is the node whose logical operation the call serves. A distillation call serves the memory write, so its cost belongs to `tool.memory.write`, and the agent that triggered the write is charged a *reference* to that cost, not the cost itself — otherwise the same tokens are double-counted when the agent's step also sums its children.

The failure mode is precisely the violation of (3) combined with (1): a retried distillation call inside a memory write, nested under an agent step, gets summed into the agent ledger *and* the memory ledger, and the retry multiplier applies to both.

Decision Boundary

The attributor must choose, per span, between **summing** (treat as independent billable event) and **collapsing** (treat as redundant attempt of an already-counted operation). The boundary is not "is this a retry" but "did this attempt incur provider-side billing." The only reliable signal is a transport-layer attestation, because:

The decision boundary is therefore: **collapse iff the span carries `gen_ai.request.billed=false` or is a fan-out loser with a confirmed cancellation; otherwise sum.** When the attestation is absent, the attributor must fail closed — refuse to attribute, emit an `attribution.unresolved` span, and route the cost to an `unattributed` bucket rather than guessing. Guessing (the common default of "sum everything") produces a ledger that is *plausible and wrong*, which is worse than an explicit gap because it silently corrupts budget alarms and per-agent chargeback.

Operational Effect

The practical consequence is that per-agent cost attribution in an OTel GenAI pipeline is a **batch reconciliation problem over closed traces, not a streaming aggregation over spans**. Any design that reduces cost in the collector as spans arrive will misattribute retries and fan-out because the owner link and cancellation markers are forward references. The reconciler must:

Without these, the failure is not a crash — it is a ledger that looks correct, passes schema validation, and drives the wrong circuit breaker. The instance that "knows" it spent 5× its budget when it spent 1× will throttle itself, drop tool calls, and degrade task success — a self-inflicted outage whose root cause is a missing boolean on a span attribute.

from dataclasses import dataclass, field
from typing import Optional


class AttributionInvariantError(RuntimeError):
    """Raised when a span tree cannot be reconciled without guessing cost ownership."""
    pass


@dataclass
class Span:
    span_id: str
    logical_op_id: str
    parent_id: Optional[str]
    agent_id: str
    tool_name: Optional[str]
    attempt: int
    input_tokens: int
    output_tokens: int
    billed: Optional[bool]          # None => attestation missing
    finish_reason: Optional[str]    # "cancelled" => fan-out loser
    fanout_owner_span_id: Optional[str] = None


@dataclass
class Ledger:
    by_agent: dict = field(default_factory=dict)
    by_tool: dict = field(default_factory=dict)
    by_memory_op: dict = field(default_factory=dict)
    unattributed: list = field(default_factory=list)


def reconcile(spans: list[Span], memory_op_prefix: str = "tool.memory.") -> Ledger:
    ledger = Ledger()
    # Group by logical operation: the unit of billing.
    ops: dict[str, list[Span]] = {}
    for s in spans:
        ops.setdefault(s.logical_op_id, []).append(s)

    for op_id, group in ops.items():
        # Resolve fan-out owner; losers are zero-cost.
        owner_id = next((s.fanout_owner_span_id for s in group
                         if s.fanout_owner_span_id), None)
        billable = [s for s in group
                    if s.finish_reason != "cancelled"
                    and (owner_id is None or s.span_id == owner_id)]

        # Attempt deduplication requires transport attestation.
        for s in billable:
            if s.billed is None:
                raise AttributionInvariantError(
                    f"span {s.span_id} (op {op_id}) lacks gen_ai.request.billed; "
                    f"cannot distinguish pre-flight abort from billed retry. "
                    f"Route to unattributed bucket, do not guess."
                )

        billed_attempts = [s for s in billable if s.billed]
        if not billed_attempts:
            continue
        # Sum across billed attempts: input tokens are re-billed per attempt.
        cost_in = sum(s.input_tokens for s in billed_attempts)
        cost_out = sum(s.output_tokens for s in billed_attempts)

        # Memory-write side effects are charged to the memory node, not the agent.
        mem_owner = next((s for s in billed_attempts
                          if s.tool_name and s.tool_name.startswith(memory_op_prefix)),
                         None)
        if mem_owner is not None:
            ledger.by_memory_op[mem_owner.tool_name] = (
                ledger.by_memory_op.get(mem_owner.tool_name, (0, 0))
            )
            prev = ledger.by_memory_op[mem_owner.tool_name]
            ledger.by_memory_op[mem_owner.tool_name] = (
                prev[0] + cost_in, prev[1] + cost_out
            )
            # Agent gets a reference edge, not the tokens.
            ledger.by_agent.setdefault(mem_owner.agent_id, (0, 0))
        else:
            a = billed_attempts[0].agent_id
            prev = ledger.by_agent.get(a, (0, 0))
            ledger.by_agent[a] = (prev[0] + cost_in, prev[1] + cost_out)
            if billed_attempts[0].tool_name:
                t = billed_attempts[0].tool_name
                pv = ledger.by_tool.get(t, (0, 0))
                ledger.by_tool[t] = (pv[0] + cost_in, pv[1] + cost_out)

    return ledger