# Where must an instance of a GenAI span attribute be resolved: the tool-call argument cardinality invariant in OpenTelemetry GenAI semantic conventions **Date of Record:** 2026 November 23 **Scope:** Applies to instrumentation and downstream processing of OpenTelemetry spans carrying `gen_ai.*` attributes where a span represents either an inference operation (`gen_ai.operation.name = "chat"` / `"text_completion"`) or a tool execution (`gen_ai.operation.name = "execute_tool"`), and where tool arguments or model outputs are recorded as attributes. Does not apply to pure metric-only telemetry, nor to spans where tool payloads are deliberately omitted per a documented redaction policy. ## Core Distinction The GenAI semantic conventions distinguish between an *inference span* that **proposes** a tool call and a *tool span* that **executes** one. The non-obvious boundary: `gen_ai.tool.call.arguments` / `gen_ai.tool.call.id` on the *inference* span describe an intent **not yet validated against a tool schema**, whereas the same-named attributes on the *tool* span describe an invocation **already dispatched**. A single inference response may contain N parallel tool calls, so the argument attribute is not a scalar — it is a serialized collection whose cardinality is only knowable when the response is fully assembled. Treating the inference span's tool-call attributes as if they were the tool span's collapses a one-to-many relationship into one-to-one and silently drops all but the first call. The attribute's *instance* must be resolved at span construction, not deferred to a consumer that cannot reconstruct it. ## What Was Observed In a production agent loop using parallel tool calls (one assistant turn emitting three `execute` requests), the inference span was emitted with `gen_ai.tool.call.id` set to the *first* call's id and `gen_ai.tool.call.arguments` set to a JSON object containing only that first call's arguments. The remaining two calls appeared as separate `execute_tool` child spans with correct ids, but their parent referenced none of them. A cost-attribution pipeline joined tool spans to inference spans by `gen_ai.tool.call.id`; two of three tool spans failed to join and were attributed to a synthetic "orphan" bucket, inflating reported tool latency ~3x. A second observation: when the model returned a tool call whose arguments were not valid JSON (a truncated stream), instrumentation emitted `gen_ai.tool.call.arguments` as the raw partial string. The tool span never executed and therefore never emitted. A consumer assuming "inference span with tool-call attributes ⇒ a corresponding tool span exists" raised no error but silently under-counted dispatch failures. A third: `gen_ai.tool.call.id` was reused across retries of the same inference request. The retry produced a new inference span with the *same* id, so a naive join produced a fan-in of two inference spans onto one tool span, double-counting token cost. ## Condition of Validity The invariant "one inference span's tool-call attributes correspond one-to-one with child tool spans" holds **only** when: 1. The inference response contains exactly one tool call, AND 2. The tool call's arguments parse as valid JSON when the inference span is closed, AND 3. The tool call id is unique per inference attempt (not reused across retries), AND 4. No tool call is dropped between proposal and dispatch (e.g., by a policy filter). Outside these conditions — the common case for any agent using parallel or streaming tool calls — the attributes are a *proposal record*, not an *execution record*, and must be modeled as a list with per-element validity, not as scalar attributes. ## Decision Boundary The decision is *where* to resolve the instance of each tool call: - **Resolve at inference-span construction (recommended):** emit one attribute pair per call using the indexed convention, and record `gen_ai.tool.call.count` equal to the number of proposals. This makes the one-to-many relationship explicit and lets consumers detect dropped calls by comparing `count` to the number of child tool spans. - **Resolve at tool-span construction only:** do *not* emit tool-call attributes on the inference span; rely solely on child spans. Valid but loses the record of *proposed-but-not-executed* calls — precisely the dispatch-failure signal. - **Do not resolve lazily in the consumer:** a consumer cannot recover per-call arguments from a single scalar attribute once the inference span is closed. Deferring resolution to the backend is the failure mode observed above. When arguments fail to parse, emit the raw payload under a distinct attribute (e.g., `gen_ai.tool.call.arguments.raw`) and set a status/error marker on the inference span; never emit a malformed value under the canonical attribute name. ## Operational Effect Instrumentation that resolves the instance at inference-span construction yields: (a) exact join cardinality between proposed and executed calls, (b) a countable dispatch-failure signal (proposed minus executed), and (c) retry-safe attribution when call ids are scoped per attempt rather than per logical request. Instrumentation that does not resolve it produces orphaned tool spans, inflated latency aggregates, and invisible dispatch failures — all of which look like healthy telemetry until someone reconciles span counts. The cost of getting this wrong is not a crash; it is a quiet, systematic bias in every downstream metric that joins on tool-call identity. ```python """Guard: enforce the tool-call instance-resolution invariant on a GenAI span.""" import json from dataclasses import dataclass, field from typing import Any class ToolCallResolutionError(RuntimeError): """Raised when a GenAI span cannot resolve the instance of a tool call.""" @dataclass class ProposedToolCall: call_id: str arguments: str # raw, possibly malformed @dataclass class GenAiSpan: operation_name: str attributes: dict[str, Any] = field(default_factory=dict) proposed_calls: list[ProposedToolCall] = field(default_factory=list) def finalize_inference_span( span: GenAiSpan, proposed_calls: list[ProposedToolCall], call_ids_seen_in_attempt: set[str], ) -> GenAiSpan: """Resolve each tool-call instance onto the inference span at close time. Enforces: * one attribute pair per proposed call (no silent collapse to scalar) * call ids unique within the attempt (retry-safe scoping) * malformed arguments quarantined, never written to canonical attribute """ if span.operation_name not in ("chat", "text_completion"): raise ToolCallResolutionError( f"tool-call attributes only valid on inference spans, got {span.operation_name!r}" ) ids = [c.call_id for c in proposed_calls] if len(ids) != len(set(ids)): raise ToolCallResolutionError( f"duplicate tool call ids within one inference attempt: {ids}" ) collisions = set(ids) & call_ids_seen_in_attempt if collisions: raise ToolCallResolutionError( f"tool call ids reused across attempts (retry scoping violated): {collisions}" ) span.attributes["gen_ai.tool.call.count"] = len(proposed_calls) for idx, call in enumerate(proposed_calls): try: json.loads(call.arguments) except json.JSONDecodeError: # Quarantine: do not emit malformed payload under canonical name. span.attributes[f"gen_ai.tool.call.{idx}.arguments.raw"] = call.arguments span.attributes[f"gen_ai.tool.call.{idx}.arguments.valid"] = False continue span.attributes[f"gen_ai.tool.call.{idx}.id"] = call.call_id span.attributes[f"gen_ai.tool.call.{idx}.arguments"] = call.arguments span.attributes[f"gen_ai.tool.call.{idx}.arguments.valid"] = True return span def assert_proposed_executed_balance( span: GenAiSpan, executed_tool_span_ids: set[str] ) -> None: """Detect dispatch failures: proposed calls with no matching tool span.""" proposed = span.attributes.get("gen_ai.tool.call.count", 0) if proposed != len(executed_tool_span_ids): raise ToolCallResolutionError( f"proposed={proposed} executed={len(executed_tool_span_ids)}: " "dispatch failure or dropped tool span" ) ```