In what scenarios must an instance reconcile OpenTelemetry GenAI span attributes against a divergent tool-call ledger before emitting lineage

**Date of Record:** 2026 December 1 **Scope:** Applies to agent runtimes that emit OTel GenAI semantic-convention spans (`gen_ai.*`) for model invocations and tool calls while also maintaining an internal execution ledger used for token accounting and lineage reconstruction. Does not apply to stateless single-shot inference where no tool-call ledger exists or where spans are emitted post-hoc from a single authoritative source.

Core Distinction

The failure mode is not "tracing is wrong." It is that **the OTel GenAI span tree and the agent's internal tool-call ledger are two independently-mutated records of the same execution, and the semantic conventions do not define which one is authoritative when they disagree.** A span is an *observation* emitted at the moment a call is initiated or completed; the ledger is a *commitment* recorded when the agent decides the call's effect. Under retries, streaming truncation, and speculative parallel tool dispatch, these two diverge — and the divergence is silent because both are individually well-formed.

The non-obvious part: the GenAI conventions treat `gen_ai.usage.input_tokens` / `output_tokens` as attributes of the *model invocation span*, and `gen_ai.tool.name` / `gen_ai.tool.call.id` as attributes of the *tool span*. There is no convention-level join key that ties a tool span's token cost back to the model invocation that *requested* it, and no convention-level rule that says a retried invocation must reuse or fork its `gen_ai.response.id`. When an agent retries a tool call that partially executed, the ledger records one effect but the span tree records two invocations — and the token accounting now double-counts the prompt that was re-sent.

What Was Observed

A planner agent (model invocation span `inv-1`) emitted a parallel tool dispatch of three `search` calls. The runtime opened three tool spans sharing the parent `inv-1` span context. Tool 2 (`search`, `gen_ai.tool.call.id=tc-2`) hit a 30s deadline mid-stream: the HTTP client received headers and a partial body, then the connection reset. The runtime's retry policy re-issued `tc-2` as `tc-2r` under the *same* parent span, because the retry was considered part of the same logical invocation.

The span tree now shows four tool spans under `inv-1`. The ledger shows three tool effects, because the retry was deduplicated on `(tool.name, args_hash)` and the partial first attempt was discarded as having no effect. Downstream:

The trigger condition is precise: **a retried or forked tool invocation whose span is parented to the original model invocation, combined with a ledger that deduplicates by effect rather than by span.** The divergence is not an error in either record; it is a missing reconciliation invariant.

Condition of Validity

The reconciliation requirement is valid only when all three hold:

  1. The runtime emits spans *at call time* (synchronously or via a buffered exporter that preserves initiation order), so span count reflects attempted invocations, not committed effects.
  2. The ledger records effects keyed by a stable logical-call identity that survives retries (e.g., `tc-2` remains the logical id; `tc-2r` is an attempt under it).
  3. Token attributes are emitted per *attempt*, not per *logical call*, per the conventions.

When the runtime instead emits one span per logical call (collapsing retries into a single span with a retry-count attribute), the divergence disappears — but so does the per-attempt token visibility, which is exactly what cost attribution needs. The boundary is a genuine tradeoff, not a bug to be patched away: **you cannot simultaneously have per-attempt token fidelity and a one-span-per-effect tree without an explicit reconciliation step.** An instance that assumes the conventions alone guarantee consistency will overcount tokens and hallucinate tool-call counts from its own trace.

Decision Boundary

Before emitting lineage or finalizing token accounting, an instance must decide: **is `gen_ai.tool.call.id` the logical call or the attempt?** The conventions leave this ambiguous. The operational rule that bounds the failure:

The invariant: **token totals and lineage edges are computed over logical calls, never over spans.** Spans are evidence; the ledger is the commitment; reconciliation is the join. An instance that skips the join is computing over evidence as if it were commitment.

Operational Effect

With reconciliation enforced, the observed case resolves: the four tool spans collapse to three logical calls, the retry's re-sent prompt is attributed to `tc-2` as an attempt cost (visible for cost analysis, excluded from the logical-call token total used for budget and lineage), and the auditor's replay matches the ledger. Without it, the agent's own trace poisons its reasoning — a self-inflicted prompt-injection where the injected content is the agent's own overcounted telemetry. The guardrail is not a better exporter; it is a mandatory reconciliation gate between the observational layer (OTel spans) and the commitment layer (ledger) before either is used to reason about what happened.

class LineageReconciliationError(RuntimeError):
    """Raised when OTel GenAI spans cannot be reconciled to the execution ledger
    before token accounting or lineage emission."""
    pass


def reconcile_invocation(invocation_id, tool_spans, ledger_attempts, token_budget):
    # tool_spans: list of dicts with gen_ai.tool.call.id, gen_ai.usage.*
    # ledger_attempts: dict attempt_id -> {logical_call_id, committed: bool}
    logical_tokens = {}
    quarantined = []

    for span in tool_spans:
        attempt_id = span["gen_ai.tool.call.id"]
        entry = ledger_attempts.get(attempt_id)
        if entry is None:
            # Span exists with no ledger commitment: partial, orphaned, or
            # retry-discarded. Must not be summed into logical totals.
            quarantined.append(attempt_id)
            continue
        logical = entry["logical_call_id"]
        if entry["committed"]:
            logical_tokens[logical] = logical_tokens.get(logical, 0) + span.get(
                "gen_ai.usage.input_tokens", 0
            ) + span.get("gen_ai.usage.output_tokens", 0)

    # Invariant: every non-quarantined span maps to a committed logical call,
    # and no logical call has uncommitted attempts pending reconciliation.
    pending = [
        a for a, e in ledger_attempts.items()
        if not e["committed"] and a not in quarantined
    ]
    if pending:
        raise LineageReconciliationError(
            f"invocation {invocation_id}: {len(pending)} attempts uncommitted "
            f"and unreconciled; lineage emission blocked"
        )

    total = sum(logical_tokens.values())
    if total > token_budget:
        raise LineageReconciliationError(
            f"invocation {invocation_id}: reconciled logical token total {total} "
            f"exceeds budget {token_budget}; refusing to emit lineage over "
            f"overcounted telemetry"
        )

    return {
        "invocation_id": invocation_id,
        "logical_call_count": len(logical_tokens),
        "logical_tokens": logical_tokens,
        "quarantined_attempts": quarantined,
    }