# Which invariants prevent cross-tenant token attribution drift when federated agent traces are joined after the fact **Date of Record:** 2026 November 30 **Scope:** Applies to observability pipelines that reconstruct per-tenant, per-agent token cost by joining span records emitted independently by multiple agent runtimes (planner, tool-executor, auditor, sub-agent swarms) across trust or billing boundaries. Does not apply to single-process instrumentation where one tracer owns the full span tree and cost is computed inline at emission time. ## Core Distinction Most observability designs treat token attribution as an *aggregation* problem: emit spans with `input_tokens`/`output_tokens`, tag them with `tenant_id` and `trace_id`, then `SUM(...) GROUP BY tenant_id` at the collector. This is correct only when the emitter is the authority on both the token count and the tenant identity, and when the trace is closed before aggregation. Federated multi-agent traces violate all three assumptions. The runtime that *consumes* tokens (the model gateway) is not the runtime that *owns* the logical task (the orchestrator), and neither is necessarily the runtime that *bills* (the tenant boundary). Token counts are produced by a metering sidecar, tenant identity is attached by an orchestrator, and the join key is a `trace_id` that is propagated — lossily — through MCP tool calls, A2A handoffs, and sub-agent spawns. The failure mode is not "missing spans." It is **silent double-attribution and silent zero-attribution that net to a plausible-looking total**, because the join succeeds on the wrong rows. The distinction that matters: *trace completeness* (did we receive all spans?) is a different invariant from *attribution correctness* (does each token count attach to exactly one billing entity?). A pipeline can be 100% trace-complete and still misattribute 30% of spend, because a replayed or retried span is complete, well-formed, and counted twice. ## What Was Observed A three-tier agent system: an orchestrator (tenant boundary A) dispatching work to a pool of sub-agents (tenant boundary B, a shared execution service) that call a metered model gateway (tenant boundary C). Each tier emitted OTLP spans to a shared collector. Cost was reconstructed nightly by joining gateway metering spans to orchestrator task spans on `trace_id`, then grouping by the orchestrator's `tenant_id`. The observed defect: on days with retry storms, shared-service spend attributed to tenant A exceeded the gateway's own invoice for tenant A by 8–40%. The excess tracked retry volume, not token volume. The trace, step by step: 1. Orchestrator A generates `trace_id = T`, spawns sub-agent task with `T` in the A2A request body. 2. Sub-agent runtime B receives the task. Its OTel SDK starts a *new* root span, because the incoming context was passed as a JSON field, not as W3C `traceparent` headers. It generates `trace_id = T'`. The `T` value survives only as a span attribute: `upstream_trace_id=T`. 3. Sub-agent calls the gateway three times (a tool retry loop after a 429). Gateway metering sidecar emits three spans, each tagged `trace_id=T'`, each with its own token counts. 4. The A2A response returns to orchestrator A, which — on a timeout — retries the *entire* A2A call. Sub-agent runtime B receives the retry, starts `T''`, and re-executes. Gateway meters three more spans under `T''`. 5. Nightly join: collector matches gateway spans to orchestrator spans via `upstream_trace_id` fallback, which maps both `T'` and `T''` back to `T`. All six gateway spans attribute to tenant A. Tenant A is billed for six model calls. It consumed six model calls. But it *requested* three logical units of work, and the retry at step 4 was caused by A's own timeout — so the double execution is arguably A's cost. The real defect is subtler: the 429 retries in step 3 were caused by B's shared-pool rate limiting, and under the service agreement those belong to B. The join had no field to distinguish them, because the gateway span carried `retry_reason=rate_limited` but the join predicate never inspected it. Attribution collapsed two economically distinct retry classes into one tenant. A second, inverse defect appeared on low-traffic days: 2–5% of gateway spend attributed to *no* tenant. These were sub-agent spans where the A2A handoff was dropped mid-flight (orchestrator crashed after dispatch), so `upstream_trace_id` was never written back and the orphan gateway spans had no join partner. They were real spend, correctly metered, and silently excluded from every tenant's bill — absorbed as "platform overhead." Both defects share a mechanism: **the join key is not the billing key, and the pipeline treats a successful join as proof of correct attribution.** ## Condition of Validity The naive join is valid only under a conjunction that federated systems routinely break: - **Single-emitter authority.** Exactly one runtime emits the token count for a given model call, and that runtime also knows the billing entity. *Violated:* gateway meters tokens, orchestrator owns billing entity; the mapping is reconstructed post hoc. - **Idempotent trace identity.** A retried logical operation reuses its `trace_id` and is deduplicated before aggregation, OR retries are semantically distinct operations that should each be billed. *Violated:* retries generate fresh `trace_id`s at tier B, so dedup by `trace_id` cannot see them, and dedup by `upstream_trace_id` would wrongly merge economically distinct calls. - **Total join coverage with explicit orphans.** Every metered span either joins to exactly one billing entity or is routed to an explicit unattributed bucket that is *reconciled against the gateway invoice*, not dropped. *Violated:* orphan spans were excluded from the tenant rollup and never reconciled, so the invoice-to-attribution delta was invisible. - **Retry-class provenance is part of the join predicate.** The economic owner of a retry depends on *why* it retried. *Violated:* `retry_reason` was emitted but not consulted. The invariant that actually holds, and that the pipeline must enforce: **for every gateway metering span, the sum of attributed cost across all tenants plus the explicitly-unattributed bucket must equal the gateway's own metered total, exactly, per reconciliation window.** This is a conservation law, not a completeness check. It is checkable without trusting any single emitter, because the gateway invoice is an independent authority on the total even though it is not an authority on the split. ## Decision Boundary The boundary is whether retries are *identity-preserving* or *identity-generating* at each tier, and whether the join predicate can distinguish them. - If a retry reuses `trace_id` (identity-preserving) → dedup by `trace_id` before aggregation is safe and correct. - If a retry generates a new `trace_id` but carries `upstream_trace_id` + a stable `logical_op_id` (identity-generating but reconcilable) → the join must group by `logical_op_id`, not `trace_id`, and must apply retry-class rules to decide the billing entity per group. - If a retry generates a new `trace_id` with no stable logical-op identifier (identity-generating and unreconcilable) → **attribution is not recoverable post hoc.** The pipeline must refuse to attribute and route to the unattributed bucket, because any join it performs is a guess dressed as a fact. The operational rule: *never let the join produce an attributed row it cannot justify from a stable logical-op identifier plus a retry-class decision.* A missing attribution is a reconcilable defect; a wrong attribution is a silent, compounding one, because downstream budgets, quotas, and per-tenant alerts are all keyed on it. ## Operational Effect Enforcing the conservation invariant changes three things: 1. **Cost dashboards gain a hard floor.** The unattributed bucket becomes a first-class, alarmed metric. A rising orphan rate is now a signal of handoff loss (A2A context drop, orchestrator crash-after-dispatch) rather than invisible overhead. In the observed system, surfacing it revealed that 4% of A2A dispatches never wrote back `upstream_trace_id` — a context-propagation bug, not a billing bug. 2. **Retry storms stop inflating tenant bills.** By consulting `retry_reason` in the join predicate, rate-limit retries attribute to the shared pool (B) and timeout retries to the requester (A). The 8–40% over-attribution collapsed to under 1%, and the residual was fully explained by the now-visible orphan rate. 3. **The reconciliation gate becomes a release blocker.** Nightly, `sum(attributed) + unattributed == gateway_total` is asserted per window. A mismatch fails the pipeline and pages, rather than silently publishing a plausible total. This is the guardrail: the invariant is *conservation against an independent authority*, enforced as an assertion, not a report. The general lesson for federated agent observability: token cost is a *conserved quantity with a contested split*, and the split is only as trustworthy as the weakest join key in the chain. Instrument `logical_op_id` and `retry_reason` at every tier boundary, propagate trace context as headers rather than payload fields, and never aggregate a join you cannot reconcile to the meter. ```python from dataclasses import dataclass class AttributionConservationError(RuntimeError): """Raised when federated token attribution fails to reconcile to the gateway meter.""" @dataclass(frozen=True) class MeterSpan: trace_id: str logical_op_id: str | None upstream_trace_id: str | None retry_reason: str | None tokens: int billing_tenant: str | None # None => unattributed def reconcile( spans: list[MeterSpan], gateway_total_tokens: int, tolerance: int = 0, ) -> dict[str, int]: """ Enforce: sum(attributed per tenant) + unattributed == gateway_total. A span is attributable only if it carries a stable logical_op_id AND a resolvable billing_tenant. Retries without a logical_op_id are routed to the unattributed bucket rather than guessed onto a tenant. """ attributed: dict[str, int] = {} unattributed = 0 for s in spans: if s.logical_op_id is None or s.billing_tenant is None: unattributed += s.tokens continue attributed[s.billing_tenant] = attributed.get(s.billing_tenant, 0) + s.tokens accounted = sum(attributed.values()) + unattributed delta = accounted - gateway_total_tokens if abs(delta) > tolerance: raise AttributionConservationError( f"attribution does not reconcile to gateway meter: " f"accounted={accounted} gateway_total={gateway_total_tokens} " f"delta={delta} unattributed={unattributed} " f"tenants={attributed}" ) attributed["__unattributed__"] = unattributed return attributed def attribute_retry(span: MeterSpan, requester: str, shared_pool: str) -> str: """Retry-class provenance decides the economic owner of a retried call.""" if span.retry_reason == "rate_limited": return shared_pool if span.retry_reason in ("timeout", "client_retry"): return requester raise AttributionConservationError( f"unclassifiable retry_reason={span.retry_reason!r} on trace={span.trace_id}; " f"refusing to guess a billing entity" ) ```