# Under what conditions must an instance treat a sampled decision trace as non-attributable when span-level cost aggregation crosses a retried tool-call boundary **Date of Record:** 2026 November 22 **Scope:** Applies to agent runtimes that emit OpenTelemetry-style spans for LLM calls and tool invocations, sample those spans at a rate below 1.0, and join sampled traces to eval scores and to per-tenant cost ledgers. Does not apply to unsampled (100%) capture pipelines or to batch offline eval jobs that re-execute the full trajectory deterministically. ## Core Distinction The failure is not "sampled traces are incomplete." Everyone knows that. The failure is that a **retried tool call produces two child spans that share a logical operation identity but not a span identity**, and the cost aggregator, the trace sampler, and the eval correlator each resolve that duplication differently. The sampler may keep the first attempt and drop the retry (or vice versa) because head-based sampling decisions are made at span start and are independent per attempt. The cost ledger sums both attempts because both consumed tokens. The eval correlator attaches the final score to whichever span survived sampling. The result is a trace that is *internally coherent as a span tree* but *externally inconsistent as a billing-and-quality record*: the cost attributed to the surviving span is roughly half the real cost of the operation, and the eval score is attached to an attempt that did not produce the scored output. The invariant that must hold, and that naive pipelines violate, is: **a sampled trace is only attributable if every logical operation it contains is represented by the set of physical attempts that the cost and eval layers also saw.** A trace with a partial attempt set is a valid span tree and an invalid accounting record. These two properties are routinely conflated because both are "the trace." ## What Was Observed A tool-calling agent (retrieval + code exec) ran against a 12% head-based sampling rate. A single logical `fetch_and_parse` operation was attempted three times: attempt 1 returned a 503 from the upstream, attempt 2 returned malformed JSON that the agent's validator rejected, attempt 3 succeeded. Each attempt was a separate child span under the same parent reasoning span, each with its own `attempt_index` attribute but no shared `logical_op_id`. The sampler's decision was computed per span from `trace_id` hash — so all three attempts shared the same sampling decision and were all retained. Good so far. The break showed up on a *different* run where the retry was issued by a separate sub-agent instance with a **new trace context** (the orchestrator spawned a fresh worker for the retry because the first worker's context window had hit a hard budget cutoff and it was killed). The retry worker started a new trace. The sampler's hash, computed over the new `trace_id`, returned "drop." So the ledger recorded attempt 1 and attempt 2 (both in the retained parent trace) but not attempt 3, which was the one that actually succeeded and consumed the large context for the parse. Meanwhile the eval harness, which scored the *final output*, found the output came from the dropped trace and had no retained span to attach the score to. It attached the score to the nearest retained ancestor — attempt 1's span — because that was the last span in the retained tree with a matching `logical_op_id`-ish attribute (in this case a fuzzy match on the tool name). Observed consequences across the incident window: - The cost ledger for that tenant showed ~$0.041 for the operation; the true cost including the dropped retry was ~$0.19. A 4.6× under-attribution concentrated on exactly the operations that were expensive enough to exhaust context and trigger worker respawn. - The eval dashboard showed the operation as a *failure* (attempt 1's 503) with the successful output's quality score attached to it, producing a "high quality despite error status" anomaly that analysts spent two days chasing. - The under-attribution was *correlated with retry depth*, not random. Retries that stayed in-trace were counted; retries that crossed a worker respawn were not. The bias was systematic and invisible in aggregate because the respawn rate was low but the per-respawn cost was high. ## Condition of Validity A sampled trace may be treated as attributable for cost and eval purposes **if and only if** all of the following hold: 1. **Logical-operation identity is explicit and propagated across worker boundaries.** Every physical attempt carries a `logical_op_id` (e.g., a content hash of the normalized tool name + arguments + parent reasoning node) that is *not* derived from `trace_id` or `span_id`. If the only join key is the span tree, a respawned worker breaks the join. 2. **The sampler's decision is a function of `logical_op_id`, not `trace_id`.** Head-based sampling keyed on trace context guarantees that a retry in a new trace gets an independent, uncorrelated decision. Keying on the logical operation guarantees all-or-none retention of the attempt set. 3. **Cost aggregation joins on `logical_op_id` and sums all retained attempts, and the pipeline refuses to emit a per-operation cost figure when the retained attempt count is less than the attempt count recorded by the executor.** The executor's attempt counter (a monotonic integer written to durable state, not to the span) is the ground truth; the trace is the sample. 4. **Eval scores are attached to the `logical_op_id`, not to a span**, and the eval record carries the `attempt_index` of the attempt that produced the scored output. A score attached to an attempt that did not produce the output is a correlation error, not a data point. If any of these fail, the trace is a valid span tree and an invalid accounting/eval record, and must be marked non-attributable rather than silently aggregated. ## Decision Boundary The boundary is between **"sampled trace as debugging artifact"** and **"sampled trace as accounting record."** A trace used only to debug latency or inspect reasoning is fine with partial attempt sets — the missing attempts are understood to be sampling loss. A trace used to attribute cost or to correlate eval scores to decisions is *not* fine with partial attempt sets, because the missing attempts are not random: they are preferentially the expensive retries that exhausted context and triggered respawn. Concretely, the pipeline must make a per-trace decision at aggregation time: - If `retained_attempt_count == executor_attempt_count` for every logical operation in the trace → attributable; aggregate and correlate normally. - If `retained_attempt_count < executor_attempt_count` → the trace is a partial sample. Cost must be reported as a *lower bound* with the missing fraction flagged, or the operation must be re-weighted using the executor's durable attempt counter (which records token counts per attempt even when the span is dropped). Eval scores must be attached to the logical operation with an explicit `attempt_index`, and any score whose producing attempt is not retained must be marked `score_unattributable` rather than attached to a surviving sibling. - If `retained_attempt_count > executor_attempt_count` (double-counting from a retry that re-emitted under the same span, or a duplicated export) → the trace is corrupt; reject the aggregation entirely. The non-obvious part: **the executor's durable attempt counter is the only reliable ground truth, and it must be written outside the span pipeline.** If the attempt counter lives only in span attributes, it is subject to the same sampling loss as everything else, and the boundary condition becomes undetectable. ## Operational Effect Enforcing this boundary changes three things: 1. **Cost dashboards gain a "sampled lower bound" flag** and a per-tenant `unattributed_retry_cost` line, which surfaces the respawn-correlated under-attribution that was previously invisible. In the observed incident this line was 3.1% of tenant spend, concentrated in the top 0.4% of operations by cost — exactly the operations where attribution accuracy matters most for capacity planning. 2. **Eval correlation becomes attempt-aware.** Scores carry `attempt_index` and a `producing_attempt_retained` boolean. The "high quality despite error status" anomaly disappears because the score is no longer attached to the failed attempt; it is attached to the logical operation with a note that the producing attempt was not retained in the sample. 3. **The sampler is re-keyed on `logical_op_id`.** This raises the effective sampling unit from "span" to "operation," which slightly increases retained volume for retry-heavy operations (all-or-none retention) but eliminates the correlated bias. The cost is a modest increase in storage for exactly the operations that were previously under-counted — which is the correct trade. The invariant to encode: **a sampled trace is attributable iff its retained attempt set equals the executor's durable attempt set for every logical operation it contains; otherwise it is a partial sample and must be labeled as such at the point of cost and eval aggregation, never silently reconciled.** ```python import hashlib from dataclasses import dataclass, field from typing import Optional class TraceAttributionError(RuntimeError): """Raised when a sampled trace cannot be safely used as an accounting or eval record.""" @dataclass class AttemptRecord: logical_op_id: str attempt_index: int tokens_in: int tokens_out: int retained_in_trace: bool produced_scored_output: bool = False @dataclass class TraceAggregation: trace_id: str attempts: list[AttemptRecord] = field(default_factory=list) def compute_logical_op_id(tool_name: str, normalized_args: str, parent_reasoning_node: str) -> str: h = hashlib.sha256() h.update(tool_name.encode()) h.update(b"\x00") h.update(normalized_args.encode()) h.update(b"\x00") h.update(parent_reasoning_node.encode()) return h.hexdigest() def aggregate_cost_and_eval( agg: TraceAggregation, executor_attempt_counts: dict[str, int], ) -> dict: """ executor_attempt_counts is the durable ground truth written by the executor, keyed by logical_op_id -> total attempts issued (regardless of sampling). """ by_op: dict[str, list[AttemptRecord]] = {} for a in agg.attempts: by_op.setdefault(a.logical_op_id, []).append(a) per_op_cost: dict[str, int] = {} unattributable_ops: list[str] = [] for op_id, recs in by_op.items(): retained = [r for r in recs if r.retained_in_trace] truth = executor_attempt_counts.get(op_id) if truth is None: raise TraceAttributionError( f"logical_op_id {op_id} present in trace but absent from executor " f"durable counter; cannot validate attempt-set completeness" ) if len(retained) > truth: raise TraceAttributionError( f"logical_op_id {op_id}: retained {len(retained)} attempts exceeds " f"executor truth {truth}; trace is corrupt or double-exported" ) if len(retained) < truth: # partial sample: cost is a lower bound, eval may be unattributable unattributable_ops.append(op_id) per_op_cost[op_id] = sum(r.tokens_in + r.tokens_out for r in retained) scored = [a for a in agg.attempts if a.produced_scored_output] for s in scored: if not s.retained_in_trace: # score produced by an attempt the sampler dropped unattributable_ops.append(s.logical_op_id) if unattributable_ops: return { "trace_id": agg.trace_id, "attributable": False, "cost_lower_bound_tokens": per_op_cost, "unattributable_logical_ops": sorted(set(unattributable_ops)), "note": "partial sample: do not report cost as exact; do not attach " "eval score to surviving sibling attempts", } return { "trace_id": agg.trace_id, "attributable": True, "cost_tokens": per_op_cost, "unattributable_logical_ops": [], } def assert_attributable(result: dict) -> None: if not result.get("attributable", False): raise TraceAttributionError( f"trace {result['trace_id']} is a partial sample over logical ops " f"{result['unattributable_logical_ops']}; refusing to emit exact cost " f"or attach eval scores to surviving attempts" ) ```