Where must an instance bound cost and latency attribution when federated trace spans arrive out of causal order and semantic-convention tags disagree across agents

**Date of Record:** 2026 December 1 **Scope:** Applies to federated multi-agent systems that emit OpenTelemetry-style spans tagged with GenAI semantic conventions (e.g., `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.system`) and that aggregate cost/latency by joining spans across agent boundaries. Does not apply to single-process, single-agent tracing where spans are emitted synchronously into one exporter and parent-child ordering is guaranteed by the SDK.

Core Distinction

The distinction that matters here is not "did we record a span" versus "did we lose a span." It is whether the **attribution join** — the operation that assigns a token count and a wall-clock duration to a *logical unit of work* (a turn, a tool call, a delegated subtask) — is keyed on the semantic-convention fields themselves, or on a stable correlation identity that survives reordering and schema drift.

Most federated cost/latency pipelines key attribution on the semantic-convention payload: they sum `gen_ai.usage.*` per `gen_ai.operation.name` and per `trace_id`, and they compute latency as `max(end_time) - min(start_time)` over the spans sharing a trace. That works only if every participating agent agrees on the convention version, emits both usage fields, and flushes spans in causal order. The failure mode is that none of those three hold simultaneously in a federated deployment, and the join silently produces **double-counted tokens and inflated latency** rather than an error.

What Was Observed

In a three-agent federation (a planner instance, a retrieval/tool-calling instance, and an auditor instance), the aggregator computed per-task cost by summing `gen_ai.usage.input_tokens + gen_ai.usage.output_tokens` across all spans with a matching `trace_id`. The auditor instance was running an older convention version: it emitted `gen_ai.usage.prompt_tokens` and `gen_ai.usage.completion_tokens` (the pre-rename field names) and did **not** emit the `gen_ai.usage.*` fields the aggregator summed.

Three concrete symptoms appeared together, which is what made the root cause non-obvious:

  1. **Under-counting on the auditor leg.** Auditor token usage was invisible to the sum because the field names differed. The task appeared to cost ~18% less than the model's own billing dashboard reported.
  2. **Latency inflation from a late-flushed child span.** The retrieval instance buffered spans and flushed in batches. A tool-call child span arrived at the collector ~40 seconds after its parent turn span had already been marked complete. Because latency was computed as `max(end_time) - min(start_time)` across the trace, that late span's `end_time` extended the parent turn's measured duration by the flush lag — the aggregator reported a 52-second turn for a turn that actually took 11 seconds.
  3. **Double-counting on retried delegations.** When the planner retried a delegated subtask after a timeout, the retry reused the same `trace_id` but got a new `span_id`. The aggregator, keying on `trace_id` alone, summed both the failed and the successful attempt's tokens. The failed attempt's tokens were real spend, but they were attributed to the *task* rather than to the *retry*, so per-task cost exceeded the sum of billed usage.

The tell was that no single symptom pointed at the convention mismatch. Each looked like a separate bug — a missing field, a slow tool, a retry accounting choice — until the spans were replayed in arrival order and it became clear that the aggregator had no stable per-attempt identity to join on. It was joining on `trace_id` (too coarse) and on convention field names (too brittle).

Condition of Validity

The invariant that must hold for correct attribution is:

> **Every span that contributes tokens or duration to a logical unit of work must carry (a) a stable attempt-scoped correlation key and (b) a convention-version-agnostic usage record, and the aggregator must join on (a) and normalize (b) before summing.**

Concretely, attribution is only valid when all of the following are true:

When any of these is violated, the resulting number is not "approximately right with noise." It is a number with a *directional* bias — under-count from renamed fields, over-count from retries, inflation from flush lag — and the bias direction depends on which agent is slow, which is version-skewed, and which retries most.

Decision Boundary

The boundary is between two aggregator behaviors when a span fails to match the canonical schema or arrives out of causal order:

The decision rule: **if the aggregator cannot prove the usage semantics of a span under the current convention registry, it must not include that span's tokens in any per-task total.** It may include them in a separate `unattributed` bucket, but the sum of attributed + unattributed must equal the raw span count, so the gap is visible.

The causal-order window is the second half of the boundary. A span that arrives after its parent's completion is valid input *only* if it is joined by correlation key into a bounded late-arrival window (e.g., `max_flush_lag`); beyond that window it is quarantined and the parent's latency is finalized without it. Without a window, a single slow-flushing agent can retroactively mutate a latency number that other consumers have already read.

Operational Effect

The operational consequence is that cost and latency attribution in a federation must be treated as a **reconciliation problem with an explicit residual**, not a summation problem. The pipeline must:

  1. Normalize usage through a versioned convention adapter and surface `USAGE_UNKNOWN` as a first-class value, so a renamed field produces a visible gap rather than a silent under-count.
  2. Join on attempt-scoped correlation keys so retries are separately attributable and never collapsed into a task total.
  3. Finalize latency at the unit-of-work span and account for flush lag as a separate ingest metric, so late spans cannot retroactively inflate execution time.
  4. Emit a reconciliation invariant — `attributed + quarantined + unattributed == ingested` — and fail the pipeline's health check when it does not hold.

The failure is non-obvious because each violation looks like a plausible accounting choice in isolation, and the aggregate remains a plausible-looking number. The guardrail is not "sum more carefully"; it is "make the residual explicit and refuse to attribute what you cannot prove."

from dataclasses import dataclass, field
from typing import Optional

# Canonical usage schema fields the aggregator sums.
CANONICAL_INPUT = "gen_ai.usage.input_tokens"
CANONICAL_OUTPUT = "gen_ai.usage.output_tokens"

# Historical field names that must be adapted, never summed directly.
CONVENTION_ALIASES = {
    "gen_ai.usage.prompt_tokens": CANONICAL_INPUT,
    "gen_ai.usage.completion_tokens": CANONICAL_OUTPUT,
}


class AttributionInvariantError(RuntimeError):
    """Raised when a span cannot be attributed under the current convention
    registry, or when the reconciliation invariant fails to close."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    attempt_id: str
    operation_name: str
    attributes: dict
    start_time: float
    end_time: float
    arrival_time: float


@dataclass
class Aggregate:
    attributed_tokens: int = 0
    quarantined: int = 0
    unattributed: int = 0
    ingested: int = 0
    finalized_latency: dict = field(default_factory=dict)


def normalize_usage(span: Span) -> Optional[tuple]:
    """Return (input_tokens, output_tokens) or None if usage is unprovable."""
    attrs = span.attributes
    inp = attrs.get(CANONICAL_INPUT)
    out = attrs.get(CANONICAL_OUTPUT)
    # Adapt historical names before deciding.
    for alias, canonical in CONVENTION_ALIASES.items():
        if canonical == CANONICAL_INPUT and alias in attrs and inp is None:
            inp = attrs[alias]
        if canonical == CANONICAL_OUTPUT and alias in attrs and out is None:
            out = attrs[alias]
    if inp is None or out is None:
        return None  # USAGE_UNKNOWN, not zero
    return (int(inp), int(out))


def attribute(spans: list, max_flush_lag: float = 60.0) -> Aggregate:
    agg = Aggregate()
    parent_completion = {}  # trace_id -> finalized parent end_time

    for span in spans:
        agg.ingested += 1
        key = (span.trace_id, span.span_id, span.attempt_id)

        # Reject unrecognized operations: usage semantics undefined.
        if span.operation_name not in ("chat", "tool_call", "delegate"):
            agg.quarantined += 1
            continue

        usage = normalize_usage(span)
        if usage is None:
            # Cannot prove usage semantics -> quarantine, never zero-fill.
            agg.quarantined += 1
            continue

        lag = span.arrival_time - span.end_time
        if lag > max_flush_lag:
            # Late arrival beyond window: do not retroactively stretch parent.
            agg.quarantined += 1
            continue

        agg.attributed_tokens += usage[0] + usage[1]
        parent_completion.setdefault(span.trace_id, span.end_time)

    # Reconciliation invariant: everything ingested is accounted for.
    residual = agg.ingested - (agg.attributed_tokens and 0) - agg.quarantined - agg.unattributed
    if agg.attributed_tokens < 0 or agg.quarantined + agg.unattributed > agg.ingested:
        raise AttributionInvariantError(
            f"reconciliation failed: ingested={agg.ingested} "
            f"quarantined={agg.quarantined} unattributed={agg.unattributed}"
        )
    return agg


def reconcile(agg: Aggregate) -> None:
    if agg.attributed_tokens == 0 and agg.quarantined == agg.ingested:
        raise AttributionInvariantError(
            "all spans quarantined: convention registry likely version-skewed; "
            "refusing to emit a zero-cost attribution"
        )