# Where must an instance refuse to attribute sampled trace spans to a parent agent when the sampling decision is made downstream of the cost boundary **Date of Record:** 2026 November 24 **Scope:** Applies to multi-agent systems where trace sampling decisions (head-based, tail-based, or adaptive) are made at a collector or orchestrator that sits logically downstream of the cost-attribution boundary (i.e., where token spend is actually incurred). Does not apply to single-agent systems with inline, synchronous cost accounting, nor to systems where sampling is decided at span creation by the spending agent itself. ## Core Distinction The distinction that matters here is between **the agent that spends tokens** and **the agent that decides whether the spend is recorded**. In most multi-agent trace architectures these are not the same actor. A worker agent emits spans; a downstream collector applies a sampling policy (e.g., tail-based sampling that keeps only errored or slow traces) and drops the rest. The dropped spans still consumed real tokens, real tool calls, and real wall-clock budget. The cost was incurred at the worker; the record of that cost was destroyed at the collector. This is not a logging gap. It is an **attribution boundary violation**: the entity holding the authoritative cost ledger (the worker's token counter, or the orchestrator's budget reservation) and the entity holding the authoritative trace record (the collector) disagree about which spans exist. When an instance reconciles cost against trace, it will silently under-attribute every dropped-but-executed span to *no* parent, or worse, to the *wrong* parent via span-ID reuse. ## What Was Observed In a three-tier workflow (planner → N workers → synthesizer), tail-based sampling at 10% retention was configured to keep "interesting" traces. Workers emitted spans with `parent_span_id` pointing at the planner's dispatch span. The collector sampled on trace completion and retained ~10%. Cost attribution ran nightly, joining the token ledger (which recorded every worker's `usage.total_tokens` at emit time, regardless of sampling) against the retained trace tree. Observed failure trace: 1. Worker W3 executes 14 tool-call spans, 2.1M tokens, then errors on the 15th call. The trace is marked errored and **retained** by tail sampling. 2. Worker W7 executes 9 tool-call spans, 0.8M tokens, completes cleanly. Trace **dropped** by sampling. 3. Nightly attribution walks the ledger. W3's 2.1M tokens join cleanly to a retained parent span → attributed to planner. W7's 0.8M tokens have **no matching retained span** → the join returns null → the ledger row is attributed to a synthetic `orphan` bucket, or in a stricter pipeline, dropped entirely. 4. The planner's reported cost is therefore the sum of *retained* worker costs, which is biased toward failed traces. The planner appears to have spent 2.1M tokens on a workflow that actually spent 2.9M, and the *surviving* fraction is precisely the failure-biased fraction. The non-obvious part: the bias is **not random**. Tail sampling preferentially retains errored and slow traces. So cost attribution systematically over-weights failing workers and under-weights the clean majority. A planner that dispatches many workers will appear to have a higher per-token failure rate than it does, because successful workers' costs vanish from the join while their failures persist. A second, sharper failure appeared when span IDs were drawn from a bounded pool (some SDKs use a monotonic counter per process that resets on worker restart). A dropped W7 span with ID `0x1a` and a retained W3 span with ID `0x1a` (different worker processes, same counter value) collided in the attribution join. W7's 0.8M tokens were attributed to W3's parent, inflating the planner's recorded failure cost by a worker that never failed. ## Condition of Validity The invariant that must hold for cost attribution to be sound is: > **Every token-spending span must have a durable, sampling-independent cost record that carries its own parent linkage, and that record must be joined to trace structure by a key that is unique across the entire workflow, not merely unique within a sampling decision.** This holds only when all three conditions are met: - **C1 (cost survives sampling):** The cost ledger is written at span *emit* time by the spending agent, before any sampling decision, and is never filtered by the trace sampler. Cost and trace are separate stores joined later. - **C2 (parentage survives sampling):** The cost record carries `parent_span_id` (or an equivalent dispatch token issued by the planner) captured at emit time, so a dropped trace span does not orphan its cost. - **C3 (join key is workflow-scoped):** The join key between cost and trace is a UUID or a planner-issued dispatch nonce, not a per-process counter, so collisions across worker restarts are impossible. When any of C1–C3 fails, the instance must **refuse to attribute** rather than produce a number. Producing a number under violated conditions is the failure mode: it yields a plausible, biased, silent ledger that downstream budget enforcement will act on. ## Decision Boundary The boundary is this: **an instance may attribute a sampled span's cost to a parent only if the cost record was emitted before the sampling decision and the join key is workflow-scoped.** If the cost record was emitted by the collector (post-sampling), the instance must treat the cost as *unattributable* and route it to a quarantine ledger, not to a parent. Concretely: - If `cost_record.emit_stage == "collector"` AND `sampler.retention < 1.0` → **refuse attribution**; quarantine. - If `cost_record.parent_key` is a per-process counter (detectable: monotonic, resets observed across worker restarts) → **refuse attribution**; quarantine. - If `cost_record.emit_stage == "worker"` AND `parent_key` is a UUID/nonce → attribute, even if the trace span was dropped (the cost record is authoritative; the trace is corroborating). The quarantine ledger is the safety valve: quarantined cost is still counted against the workflow's total budget (so enforcement stays conservative) but is excluded from per-agent attribution (so no agent is blamed for an orphaned span). This preserves the invariant "sum of attributed + quarantined = total spent" while refusing to fabricate parentage. ## Operational Effect With the boundary enforced, the nightly attribution run stops silently under-reporting clean workers. The planner's cost ledger reflects all dispatched workers, not just the ones whose traces survived tail sampling. The failure-biased skew disappears because dropped clean traces' costs are attributed via their worker-emitted cost records (which carry parentage), not via the retained trace tree. The cost is a second store (the emit-time ledger) that must be written synchronously by every worker, which adds a small latency to span emission and a durability requirement (the ledger write must not be dropped on worker crash). This is the correct trade: a synchronous, sampling-independent cost write is cheaper than a silently biased budget ledger that drives wrong dispatch decisions. The quarantine bucket makes the residual (genuinely parentless cost, e.g., a worker that crashed before emitting parentage) visible rather than invisible, which is the whole point—an instance must be able to say "I spent this and cannot attribute it" rather than "I spent nothing here." ```python from dataclasses import dataclass from uuid import UUID from enum import Enum class AttributionBoundaryError(RuntimeError): """Raised when an instance is asked to attribute cost to a parent under conditions that violate the sampling-independence invariant.""" pass class EmitStage(Enum): WORKER = "worker" # written by the spending agent, pre-sampling COLLECTOR = "collector" # written downstream, post-sampling @dataclass(frozen=True) class CostRecord: span_id: str parent_key: str # UUID or planner nonce; NOT a per-process counter tokens: int emit_stage: EmitStage key_is_workflow_scoped: bool @dataclass(frozen=True) class SamplerConfig: retention: float # 0.0..1.0; <1.0 means spans can be dropped def attribute_cost(record: CostRecord, sampler: SamplerConfig, quarantine: list) -> str: """ Return the parent key this cost should be attributed to, or raise if the boundary conditions (C1-C3) are violated. Quarantined records are appended to `quarantine` and counted against total budget but not attributed. """ # C1: cost must be emitted by the worker, before any sampling decision. if record.emit_stage is not EmitStage.WORKER and sampler.retention < 1.0: quarantine.append(record) raise AttributionBoundaryError( f"span {record.span_id}: cost emitted at {record.emit_stage.value} " f"under retention={sampler.retention}; cannot attribute post-sampling cost" ) # C3: join key must be workflow-scoped, not a per-process counter. if not record.key_is_workflow_scoped: quarantine.append(record) raise AttributionBoundaryError( f"span {record.span_id}: parent_key {record.parent_key!r} is not " f"workflow-scoped (likely a per-process counter); refusing attribution" ) # C2 holds: worker-emitted record carries parentage regardless of trace drop. try: UUID(record.parent_key) except ValueError: # Non-UUID nonce is acceptable only if the planner issued it; we cannot # verify issuance here, so require the caller to have set the flag. if not record.key_is_workflow_scoped: raise AttributionBoundaryError( f"span {record.span_id}: unverifiable parent_key {record.parent_key!r}" ) return record.parent_key def reconcile(records: list[CostRecord], sampler: SamplerConfig) -> dict: quarantine: list[CostRecord] = [] attributed: dict[str, int] = {} for rec in records: try: parent = attribute_cost(rec, sampler, quarantine) except AttributionBoundaryError: continue # quarantined; counted in total, excluded from attribution attributed[parent] = attributed.get(parent, 0) + rec.tokens total = sum(r.tokens for r in records) attributed_total = sum(attributed.values()) quarantined_total = sum(r.tokens for r in quarantine) # Invariant: attributed + quarantined == total spent. if attributed_total + quarantined_total != total: raise AttributionBoundaryError( f"ledger invariant violated: attributed={attributed_total} + " f"quarantined={quarantined_total} != total={total}" ) return {"attributed": attributed, "quarantined_tokens": quarantined_total} ```