# Where must an instance reconcile OpenTelemetry GenAI span attributes against a mutable tool-call contract before closing a parent agent span? **Date of Record:** 2026 November 25 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.response.finish_reasons`) for tool-call child spans and model-invocation metrics, and that close a parent `invoke_agent` span after a multi-turn tool loop. Does not apply to single-shot completions with no tool fan-out, nor to runtimes where spans are emitted only at process exit by an out-of-band collector. ## Core Distinction The failure is not "missing telemetry." It is **attribute/contract skew at span-close time**: the tool-call child span was stamped with the *declared* schema of the tool (name, parameter set, unit semantics) at invocation, but the tool's *effective* schema — discovered mid-call via a schema-negotiation response, a retry with a narrowed argument set, or a fallback model — changed before the parent `invoke_agent` span closed. OTel GenAI conventions treat `gen_ai.tool.name` and `gen_ai.tool.call.id` as *identifiers*, not as versioned contracts. When the effective schema drifts, the child span's attributes remain internally consistent but become **semantically inconsistent with the parent span's aggregated metrics**, because `gen_ai.usage.*_tokens` on the parent were summed across model invocations that operated under two different tool schemas. The distinction from ordinary trace loss: every span is present and well-formed; the *invariant* that "a parent span's token totals are attributable to a single tool contract" is silently violated. ## What Was Observed A retrieval-augmented agent loop invoked `search_documents` with an initial schema declaring `top_k: int` and returning `chunks[]`. On the third tool turn, the MCP server responded with a schema-negotiation error (`-32602 invalid params`) and the runtime retried with `top_k` coerced to a string and a new `filter` object added — an effective schema the child span did not record, because the child span's `gen_ai.tool.name` was set once at invocation and `gen_ai.tool.call.id` was regenerated on retry. Three child spans existed for what the parent counted as one logical tool call. The parent `invoke_agent` span closed with `gen_ai.usage.input_tokens` summed across all three model invocations (including the retry's re-sent context), but the dashboard's per-tool token attribution — computed by joining child `gen_ai.tool.name` to parent usage — undercounted by the retry's tokens and overcounted the tool's *effective* cost per call. Separately, a second agent instance in the same swarm emitted the same `gen_ai.tool.call.id` prefix because the ID was derived from `hash(tool_name + turn_index)` rather than a UUIDv7, causing the collector's span deduplication to drop one instance's retry span entirely. The observable symptom was a **bimodal token-per-tool-call distribution** in the metrics backend: one peak for clean calls, one for retried calls, with no attribute distinguishing them. ## Condition of Validity The invariant holds only if, at the moment the parent `invoke_agent` span is closed, the runtime can assert: 1. Every child tool span carries a `gen_ai.tool.call.id` that is globally unique across concurrent instances (UUIDv7 or instance-scoped monotonic counter — not a content hash). 2. Every retry of the same logical tool call is either (a) recorded as a distinct child span with an explicit `retry.attempt` attribute, or (b) collapsed into one child span whose attributes reflect the *final effective* schema, not the declared one. 3. The parent's `gen_ai.usage.*_tokens` are partitioned per child `gen_ai.tool.call.id` such that the sum of child-attributed tokens equals the parent total (a conservation invariant). 4. If schema negotiation changed the tool contract mid-loop, at least one attribute on the child span (`gen_ai.tool.schema.version` or an equivalent custom attribute) records the effective version, so the join is reconstructible. If any of (1)–(4) is unenforceable at close time, the parent span must not be closed with aggregated usage attributes — it must be closed with usage attributes absent and a `gen_ai.agent.telemetry_degraded=true` flag, forcing the metrics pipeline to exclude it from per-tool attribution rather than silently mis-attribute. ## Decision Boundary The runtime must decide, **before emitting the parent span's closing event**, whether the loop's tool calls are *contract-stable* or *contract-drifted*. The boundary: - **Contract-stable:** all child spans share one effective schema version and one call-ID namespace; close normally with summed usage. - **Contract-drifted:** any child span's effective schema differs from the parent's declared tool set, or any call-ID collided across instances; close with usage attributes withheld and a degradation flag, and emit a separate `gen_ai.tool.schema_drift` event span. The non-obvious part: the decision cannot be made from the child spans alone, because a retried span that succeeded looks identical to a first-try span. The runtime must maintain a **per-parent-span call-ID ledger** (a set of call-IDs seen, plus a schema-version set) and check it at close. This ledger is the guardrail; without it, drift is invisible. ## Operational Effect Withholding summed usage on drifted parents moves the error from *silent mis-attribution* to *explicit exclusion*. Downstream per-tool cost dashboards lose coverage on drifted loops (typically 3–8% of multi-tool agent runs) but stop reporting bimodal distributions that mislead capacity planning. The `gen_ai.tool.schema_drift` event span gives the platform team a queryable signal to fix the tool contract (usually a schema-negotiation bug on the MCP server side) rather than a metrics bug. The call-ID ledger also closes the cross-instance dedup hole, because UUIDv7 IDs cannot collide and the collector's dedup becomes correct by construction. ```python import uuid from dataclasses import dataclass, field from typing import Optional class TelemetryContractDriftError(RuntimeError): """Raised when a parent agent span cannot be closed with summed usage because its child tool spans drifted in schema or call-ID namespace.""" pass @dataclass class ToolCallSpan: call_id: str tool_name: str schema_version: str input_tokens: int output_tokens: int retry_attempt: int = 0 @dataclass class ParentAgentSpan: span_id: str declared_tool_schemas: dict # tool_name -> schema_version children: list = field(default_factory=list) usage_attributable: bool = True degraded: bool = False def register_child(parent: ParentAgentSpan, child: ToolCallSpan) -> None: if child.call_id in {c.call_id for c in parent.children}: # Same call-id reused across a retry or across instances: the collector # will deduplicate and one span will vanish. Force a distinct id. raise TelemetryContractDriftError( f"call_id collision on {child.call_id!r} for tool {child.tool_name!r}; " f"regenerate with uuid7() before appending" ) parent.children.append(child) def close_parent_span(parent: ParentAgentSpan) -> ParentAgentSpan: seen_schemas = {c.tool_name: c.schema_version for c in parent.children} drifted = { name: ver for name, ver in seen_schemas.items() if parent.declared_tool_schemas.get(name) != ver } if drifted: # Cannot attribute summed usage to a single contract. parent.usage_attributable = False parent.degraded = True # Emit gen_ai.tool.schema_drift event span here; do NOT raise, because # the agent loop itself succeeded — only telemetry is degraded. return parent def emit_usage(parent: ParentAgentSpan) -> dict: if not parent.usage_attributable: raise TelemetryContractDriftError( f"parent span {parent.span_id!r} is schema-drifted; " f"refusing to emit gen_ai.usage.* attributes (would mis-attribute " f"tokens across {len(parent.children)} child tool spans)" ) return { "gen_ai.usage.input_tokens": sum(c.input_tokens for c in parent.children), "gen_ai.usage.output_tokens": sum(c.output_tokens for c in parent.children), } def uuid7() -> str: return str(uuid.uuid4()) # stand-in; real impl is time-ordered ```