# Which invariants prevent span-attribution collapse when a traced agent trajectory is replayed across a cost-accounting boundary **Date of Record:** 2026 December 1 **Scope:** Applies to agents whose execution is instrumented with span-level trajectory tracing (OpenTelemetry-style parent/child spans, one span per LLM call and per tool call) and whose cost and hallucination tags are attributed per span, then reconciled against a billing or audit ledger. Does not apply to single-call, single-span inference where no parent-child tree exists and no replay reconciliation is performed. ## Core Distinction The failure here is not "the agent hallucinated" and it is not "the trace was incomplete." It is a **span-identity invariant violation**: the tracer treats a span's identity as its position in the execution tree, while the cost ledger treats a span's identity as its `(trace_id, span_id)` pair. When an agent retries, re-plans, or resumes from a checkpoint, the execution tree is *rewritten* — a node that was a leaf becomes a parent, a tool call is re-issued under a new span, and the LLM call that produced the hallucinated token is re-emitted as a sibling rather than a child. Cost and hallucination tags were attached to the *old* tree shape. On replay, the tag-to-span binding silently re-resolves to a different node. The distinction that matters operationally: **a trajectory trace is a mutable execution artifact; a cost attribution is an immutable accounting record.** Any system that lets the second derive by re-walking the first has coupled an audit invariant to a non-deterministic artifact. ## What Was Observed An agent executing a 14-step research task with three tool calls (web search, calculator, file write) emitted a clean span tree on the first pass. At step 9, the web-search tool returned a schema-valid but semantically empty result (`{"results": []}`), which the model misread as "no results exist" and began to confabulate citations. The confabulated citation text was tagged as a hallucination span by a post-hoc span classifier, bound to `span_id=0x7f3a` (the LLM call at step 9). The orchestrator's retry policy then fired — not on the hallucination, but on a downstream file-write timeout at step 12. The retry re-entered the plan at step 8, re-issued the search tool call, received the same empty result, and this time the model *did* handle it correctly. The re-execution produced a *new* LLM call span at the same logical step, `span_id=0x9c11`, with no hallucination tag. On ledger reconciliation: - The cost ledger summed all emitted spans: 14 original + 5 re-executed = 19 billed LLM/tool spans, but the logical task had 14 steps. **Cost over-attribution of 35%.** - The hallucination tag on `0x7f3a` remained in the trace store, but the *replayed* trace tree had `0x7f3a` as an orphaned span — its parent had been re-parented under the retry subtree. The hallucination report counted one hallucination; the *corrected* trajectory contained zero. **Hallucination tag survived a retry that invalidated it.** - The tool-call cost for the calculator (cheap) was attributed to the web-search span (expensive) because the replay renumbered sibling indices and the attribution key was `(trace_id, sibling_index)` rather than `(trace_id, span_id)`. The critical observation: **no component logged an error.** The tracer emitted valid spans. The cost ledger summed valid rows. The hallucination classifier tagged a valid span. The corruption was entirely in the *join* between them, and the join was implicit. ## Condition of Validity The invariant that must hold for span-attributed cost and hallucination tags to be trustworthy is: > **For every span `s`, the tuple `(trace_id, span_id)` is globally unique and immutable for the lifetime of the trace, and every tag or cost row referencing `s` is written exactly once against that tuple and never re-resolved by tree position.** This decomposes into three sub-invariants that each fail independently: 1. **Identity immutability.** `span_id` must not be reused across retries. A retry is a *new* span, not a re-execution of the old one. Violated by tracers that key spans on `(step_index, attempt_agnostic)`. 2. **Tag write-once.** A hallucination tag, once written against `span_id=X`, must never be migrated to `span_id=Y` when the tree is re-parented. Violated by post-hoc classifiers that re-walk the final tree and re-bind tags by logical step. 3. **Attribution closure.** The set of spans in the cost ledger must equal the set of spans in the trace store, joined on `(trace_id, span_id)`, with no row admitted by tree position or sibling index. The condition of validity is *not* "the agent didn't retry." Retries are normal. The condition is that **the accounting join is by immutable identity, not by structural position.** ## Decision Boundary The boundary between safe and unsafe operation is whether the cost/hallucination join is **positional** or **identity-based**: - **Positional join (unsafe):** attribution keyed on `(trace_id, step_index)` or `(trace_id, sibling_index)` or "the Nth LLM span under the root." Any retry, re-plan, or checkpoint-resume that changes tree shape silently re-binds attribution. This is the default in most tracer SDKs because step indices are what humans read in the UI. - **Identity join (safe):** attribution keyed on `(trace_id, span_id)` where `span_id` is minted at span creation and never reused. Retries mint new IDs. Re-parenting does not touch IDs. The join is a set operation, and a missing span on either side is a hard reconciliation error, not a silent zero. The boundary is crossed the moment an agent's execution can diverge from its recorded tree — which is *always* true for any agent with retry, re-plan, checkpoint-resume, or speculative execution. For a strictly linear, no-retry agent, positional and identity joins coincide and the distinction is invisible. That invisibility is the trap: the bug ships in the linear case and detonates in the first retry. A secondary boundary: hallucination tagging performed **post-hoc by re-walking the final trace** is unsafe under any retry, because the final tree no longer contains the span that actually produced the confabulation. Tagging must be performed **inline at span close**, against the span's own output, before any re-parenting can occur. ## Operational Effect When the invariant holds, cost over-attribution is bounded by the retry count (each retry is a billed span, correctly attributed to the retry attempt, and the ledger can report "step 9 cost $0.04 across 2 attempts") and hallucination tags are *per-attempt*, so a retry that fixes a hallucination shows one tagged attempt and one clean attempt — which is the operationally correct signal. The agent's self-correction becomes visible rather than erased. When the invariant is violated, three compounding effects occur: 1. **Silent cost inflation.** Retried spans are double-counted or mis-attributed to the wrong tool, and the ledger cannot distinguish "expensive step" from "cheap step executed twice." 2. **Hallucination tag laundering.** A hallucination that was corrected by retry either persists in the report (false positive) or is erased by re-binding to the clean retry span (false negative). Both destroy the classifier's calibration signal. 3. **Replay divergence.** Re-running the trace for audit produces a different attribution than the live run, because the join is order-dependent. The audit cannot reproduce the bill. The guardrail is architectural, not procedural: mint `span_id` at creation from a monotonic counter plus a per-attempt nonce, write tags inline at span close, and make the cost-ledger join a **set-equality assertion** that raises on any span present in one store and absent in the other. A reconciliation that tolerates missing spans is not a reconciliation. ```python from dataclasses import dataclass, field from typing import Dict, Set, Tuple class SpanAttributionCollapse(RuntimeError): """Raised when cost/hallucination attribution cannot be joined to the trace store by immutable span identity. Indicates a positional join, a reused span_id across retries, or a tag written against a span that no longer exists in the reconciled trace.""" pass @dataclass(frozen=True) class Span: trace_id: str span_id: str # minted once at creation, never reused across retries attempt: int # retry attempt index; new attempt => new span_id logical_step: int # human-facing; NOT a join key cost_usd: float = 0.0 hallucination_tagged: bool = False @dataclass class CostLedger: rows: Dict[Tuple[str, str], float] = field(default_factory=dict) def record(self, span: Span) -> None: key = (span.trace_id, span.span_id) if key in self.rows: # write-once invariant: a span's cost is recorded exactly once raise SpanAttributionCollapse( f"duplicate cost row for span {key}; span_id reused across retries" ) self.rows[key] = span.cost_usd def reconcile(trace_spans: Set[Span], ledger: CostLedger) -> Dict[str, float]: """Join cost ledger to trace store by (trace_id, span_id) identity. Any asymmetry is a hard error — never silently zero.""" trace_keys = {(s.trace_id, s.span_id) for s in trace_spans} ledger_keys = set(ledger.rows.keys()) missing_in_ledger = trace_keys - ledger_keys missing_in_trace = ledger_keys - trace_keys if missing_in_ledger: raise SpanAttributionCollapse( f"spans present in trace but unbilled: {sorted(missing_in_ledger)}" ) if missing_in_trace: # classic positional-join symptom: ledger references a span_id that # the re-parented trace no longer contains raise SpanAttributionCollapse( f"ledger references spans absent from reconciled trace: " f"{sorted(missing_in_trace)}" ) # hallucination tags must be per-attempt and per-span, never migrated tagged = {(s.trace_id, s.span_id) for s in trace_spans if s.hallucination_tagged} if not tagged.issubset(trace_keys): raise SpanAttributionCollapse("hallucination tag bound to non-existent span") return {f"{t}:{s}": ledger.rows[(t, s)] for (t, s) in trace_keys} ```