# What happens when an instance samples its own trace spans under a federated cost ceiling: attribution drift at the sampling boundary **Date of Record:** 2026 November 28 **Scope:** Applies to multi-agent systems where each agent instance emits its own OpenTelemetry-style spans, applies local head-based or tail-based sampling before export, and where a federated cost-attribution layer sums per-agent token/USD counters to enforce a shared budget ceiling. Does not apply to centralized collectors that receive 100% of spans, nor to single-agent systems with no cross-instance budget arbitration. ## Core Distinction There are two distinct notions of "cost" in a federated agent mesh, and they diverge the moment any instance samples its own spans before export: 1. **Incurred cost** — the ground-truth provider billing event: tokens actually sent to and returned from the model, plus tool-call charges, attributable to a specific agent instance and a specific causal chain. 2. **Observed cost** — the sum of `gen_ai.usage.input_tokens`, `output_tokens`, and derived USD counters carried on spans that actually reached the federated collector. Under unsampled export these are equal. Under *local* sampling they are not, and the inequality is not a uniform scale factor. Head-based sampling drops entire traces uniformly, which preserves ratios. The failure mode here is **non-uniform local sampling**: an agent instance samples by its *own* criteria (e.g., drop spans below a latency threshold, or sample at 10% but always keep errors), so the surviving spans are a biased subsample of the cost distribution. The federated ceiling is then enforced against a biased estimate, and the budget controller's decisions become systematically wrong in a direction that depends on each instance's sampling policy — which the controller cannot see. ## What Was Observed A four-agent pipeline (planner → retriever → synthesizer → critic) shared a federated ceiling of $50/day. Each instance ran tail-based sampling locally: keep 100% of error spans, keep 20% of success spans, and — critically — the synthesizer additionally kept 100% of spans exceeding 8k output tokens because those were "interesting." The collector received ~22% of spans. The budget controller summed observed cost and reported $31.40 at 18:00. Ground-truth provider billing at the same instant was $47.90. The controller believed it had $18.60 of headroom and admitted three additional long-running critic jobs. By 19:10 the actual spend crossed $50 while observed spend read $34.10; the controller did not trip the ceiling. The overrun was $6.20 and, more damagingly, every per-agent attribution percentage the controller reported was inverted: the synthesizer was reported as 19% of spend (it was 41%), because its expensive spans were the ones *retained* by the >8k-token rule while the planner's many cheap spans were *dropped* at 20%. The retention policy correlated with cost magnitude, and the correlation differed per instance. The trace-level symptom was a set of `gen_ai.usage.*` sums that reconciled to a clean-looking total but whose per-`service.name` breakdown was non-representative. Nobody noticed until a post-hoc reconciliation against provider invoices. ## Condition of Validity The invariant that must hold for federated cost attribution to be sound is: > For every instance `i` and every cost-relevant span class `c`, the expected observed cost contribution `E[observed_i,c]` must equal `incurred_i,c` up to a *single, known, instance-independent* scale factor `k`, and the estimator must be unbiased per instance. Local sampling violates this whenever the sampling probability `p_i(span)` is correlated with the span's cost `cost(span)`. Formally, the Horvitz–Thompson estimator `Σ cost(span)/p_i(span)` is unbiased only if `p_i` is known to the aggregator and applied as a weight. Local samplers almost never export their inclusion probabilities, and tail-based samplers cannot — the decision to keep a span depends on the span's own completion, so `p_i` is a function of the realized value, not a pre-drawn design probability. The condition therefore fails in exactly three recognizable configurations: - **Value-correlated tail sampling** (keep-errors, keep-long-spans, keep-expensive) — `p` depends on cost or on a proxy correlated with cost. - **Per-instance rate heterogeneity** — different agents sample at different rates with no shared denominator, so summed counts are not comparable across instances. - **Adaptive sampling under load** — the sampler tightens its rate as throughput rises, which correlates sampling probability with request volume and hence with burst cost. ## Decision Boundary The architectural boundary is: **the cost-attribution path must never consume a sampled span stream as its cost source.** Sampling is for debugging and quality analysis; billing and ceiling enforcement must read from a separate, unsampled accounting channel. Concretely: - Emit cost counters (token usage, tool charges, per-call USD) on a **dedicated accounting event** that is never subject to the trace sampler — a separate exporter, a separate pipeline, or a synchronous write to the budget ledger at call completion. - If sampling must be used for cost (e.g., to bound export volume), the sampler **must export inclusion probabilities** as a span attribute (`sampling.probability`) and the aggregator **must** apply Horvitz–Thompson weighting; and tail-based samplers must be forbidden from this path because they cannot supply a valid design probability. - The budget controller must **fail closed**: if the accounting channel is stale or missing for an instance beyond a configured window, it must treat that instance's spend as unbounded (or at its historical max) rather than zero. Zero-fill on missing accounting is the specific bug that let the observed $34.10 read as authoritative. The decision boundary is crossed the moment a controller's ceiling check reads a number whose provenance is a sampled stream and whose sampling design is not exported and weighted. Below that line, sampling is harmless. Above it, the controller is enforcing a budget against a biased estimator whose bias it cannot see. ## Operational Effect When the boundary is crossed, three effects compound: 1. **Ceiling breach without alarm.** The controller under-counts precisely for the agents whose spans are most likely to be dropped, which are the high-volume cheap agents; the expensive agents are over-retained and over-counted, so aggregate spend is under-counted at the margin where it matters. The ceiling trips late or not at all. 2. **Attribution inversion.** Per-agent percentage breakdowns become non-monotonic in true cost; capacity decisions (which agent to throttle) target the wrong instance. In the observed case the planner was throttled while the synthesizer — the real cost driver — was untouched. 3. **Unreconcilable audits.** Because tail-based inclusion probabilities are unexportable, no post-hoc reweighting can recover ground truth from the collected spans. The only recovery path is the provider invoice, which is coarse-grained and delayed. The guardrail that bounds this: a **dual-channel invariant** — the accounting channel is unsampled and append-only, the trace channel is sampled and lossy, and the two are reconciled on a schedule with an explicit tolerance. Any drift beyond tolerance halts admission of new work until reconciled. The controller never reads the trace channel for money. ```python from dataclasses import dataclass from typing import Mapping class AttributionDriftError(RuntimeError): """Raised when sampled trace cost diverges from unsampled accounting beyond tolerance.""" @dataclass(frozen=True) class CostWindow: instance_id: str observed_usd: float # sum over spans that reached the collector incurred_usd: float # unsampled accounting ledger sampling_probability: float | None # None => tail-based / unexportable accounting_stale_s: float class FederatedBudgetController: def __init__(self, ceiling_usd: float, drift_tolerance: float = 0.02, max_staleness_s: float = 30.0) -> None: self.ceiling_usd = ceiling_usd self.drift_tolerance = drift_tolerance self.max_staleness_s = max_staleness_s def reconcile(self, windows: Mapping[str, CostWindow]) -> float: total_incurred = 0.0 for inst, w in windows.items(): if w.accounting_stale_s > self.max_staleness_s: # Fail closed: never zero-fill missing accounting. raise AttributionDriftError( f"instance {inst} accounting stale {w.accounting_stale_s:.1f}s; " "refusing to enforce ceiling against sampled data" ) if w.sampling_probability is None: raise AttributionDriftError( f"instance {inst} uses tail-based sampling with no exported " "inclusion probability; observed cost is unusable for billing" ) # Horvitz-Thompson reweight of the observed sample. reweighted = w.observed_usd / w.sampling_probability drift = abs(reweighted - w.incurred_usd) / max(w.incurred_usd, 1e-9) if drift > self.drift_tolerance: raise AttributionDriftError( f"instance {inst} attribution drift {drift:.1%} exceeds " f"tolerance {self.drift_tolerance:.1%}" ) total_incurred += w.incurred_usd return total_incurred def admit(self, windows: Mapping[str, CostWindow], next_job_usd: float) -> bool: spent = self.reconcile(windows) if spent + next_job_usd > self.ceiling_usd: return False return True ```