# Where must an instance refuse to emit a GenAI span when tool-call attribution cannot be reconstructed from the parent context **Date of Record:** 2026 November 27 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*`) where tool calls execute across a context boundary (async worker, sub-agent, MCP transport hop, or resumed checkpoint). Does not apply to single-turn, single-process instrumentation where the tool executor shares the caller's `Context` object synchronously. ## Core Distinction There are two mutually incompatible things an instrumented agent can do when it invokes a tool whose execution is decoupled from the span that requested it: 1. **Emit a `gen_ai.tool.call` span anyway**, reconstructing attribution from what is locally available (the tool name string, a thread-local "current span," or a freshly minted trace ID). 2. **Refuse to emit**, and instead propagate an explicit attribution token (trace ID + parent span ID + a hash of the arguments) that the executor must echo back before a span is created. The failure is not "missing spans." Missing spans are a visible, debuggable gap. The failure is **orphaned spans that look correct**: a `gen_ai.tool.call` child span that is syntactically valid, carries a plausible `gen_ai.tool.name` and `gen_ai.usage.output_tokens`, and is stitched under the *wrong parent* — typically the trace root, or the executor's own ambient span. Downstream, token accounting sums cleanly, latency histograms populate, and the semantic-convention validator passes. Nothing is red. The attribution is simply false. The invariant that must be enforced: **a `gen_ai.tool.call` span may only be emitted if the executor can prove, from data it received over the transport, which `gen_ai` parent span requested it.** Absent that proof, the correct behavior is to emit a *degraded* record (a span with `gen_ai.tool.call.attribution = "unresolved"` and no parent link to a reasoning span) or to drop the span and increment a counter — never to guess a parent. ## What Was Observed A planner agent (`gen_ai.operation.name = "chat"`, span `S_plan`) emits a tool call to a code-execution worker over an async queue. The worker runs in a separate process with its own `TracerProvider` and its own `Context`. The instrumentation in the worker does the natural thing: - It reads `gen_ai.tool.name` from the request payload (present, correct). - It reads the "current span" from its own context — which is `None`, because nothing propagated. - It falls back to `trace.get_current_span()`, which returns the non-recording `INVALID_SPAN`, so the SDK starts a **new root span** with a fresh trace ID. The result: `S_tool` has `parent_span_id = 0000000000000000`. It is a root. Its `gen_ai.usage.input_tokens` and `output_tokens` are real. The collector accepts it. But `S_plan`'s trace now contains *zero* tool spans, and the tool span lives in a one-span trace that no one correlates to the reasoning that caused it. The second, subtler variant is worse. Suppose the worker *does* have ambient context — because it is a long-lived pool worker that already handled a previous request from a *different* agent instance. If the instrumentation reads `get_current_span()` without clearing context between tasks, `S_tool` is parented under the **previous request's span**. The trace is now internally consistent, fully linked, and completely wrong: agent A's tool call is attributed to agent B's reasoning span. Token accounting for B inflates; A's appears to have called a tool it never called. This is a context-bleed attribution error, and it survives every schema check because the schema only validates field presence, not causal truth. The trigger condition is precise: **the tool executor's `Context` does not contain the requesting `gen_ai` span, and the instrumentation has a non-null fallback parent (ambient span, pool-worker residue, or a synthetic root) rather than failing closed.** ## Condition of Validity The guardrail is only sound under a stated precondition, and stating it is the point: > A `gen_ai.tool.call` span is *valid* if and only if the tuple `(trace_id, parent_span_id, gen_ai.tool.name, args_digest)` present at execution time equals the tuple the requester recorded at dispatch time. `args_digest` is a stable hash of the serialized tool arguments. It is the load-bearing element most instrumentation omits. Trace ID and parent span ID alone are insufficient because they can be *correct-but-stale*: a resumed checkpoint may replay a dispatch with the same span IDs but different arguments (the agent re-planned and re-invoked the tool with new inputs while reusing the span). Without the digest, the executor cannot distinguish "this is the call my parent asked for" from "this is a different call that happens to share a parent." When the tuple does not match — including the case where `parent_span_id` is absent because propagation failed — the invariant is violated and the span must not be emitted as an attributed child. This is a **fail-closed** rule. It is valid only when the transport actually carries the tuple end-to-end; if the queue strips trace context (a common default in older task-queue libraries), the rule will fire constantly and you must fix propagation, not relax the rule. ## Decision Boundary The boundary between "emit attributed" and "emit degraded/refuse" is a single comparison, and it must live in the executor, not the requester: - **Emit attributed child** iff `parent_span_id` is non-zero AND the resolved parent span's `gen_ai.operation.name` is a reasoning operation (`chat`, `invoke_agent`, `execute_tool`) AND `args_digest` matches the dispatch record. - **Emit degraded** (root span, `gen_ai.tool.call.attribution = "unresolved"`, `attribution.reason` set to `missing_parent` | `digest_mismatch` | `parent_not_genai`) if any condition fails but you still want the token/latency data. - **Refuse entirely** (drop, increment `gen_ai.attribution.dropped` counter) when the parent resolves to a span from a *different* trace than the one the requester claims — this is the context-bleed case and the data is actively harmful. The non-obvious part: **a parent that exists but is not a `gen_ai` operation span is a mismatch, not a success.** Parenting a tool call under an HTTP server span because that's the ambient context produces a span tree that looks structurally fine and semantically lies about which reasoning step caused the call. ## Operational Effect Enforcing this boundary changes three things downstream: 1. **Token accounting becomes causal, not additive.** `gen_ai.usage.*_tokens` summed under a reasoning span now reflects only the tool calls that reasoning span actually issued. Previously, pool-worker bleed silently moved tokens between agent instances, and cost dashboards attributed spend to the wrong tenant. 2. **Trace completeness becomes monotonic under retries.** Because `args_digest` is in the tuple, a replayed dispatch with changed arguments produces a `digest_mismatch` degraded span rather than a duplicate attributed child — the duplicate that used to double-count tool latency in p95. 3. **Failures become loud at the boundary.** A propagation regression (queue upgrade strips `traceparent`) now shows up as a spike in `attribution = "unresolved"` within one deploy cycle, instead of as a slow drift in "average tools per agent turn" that no one notices for a quarter. The cost is that you must carry the attribution tuple across every transport hop and thread it through the tool executor's signature. That is the invariant. The alternative — trusting ambient context — is not instrumentation. It is fabrication with a schema. ```python import hashlib import json from dataclasses import dataclass class GenAIAttributionError(RuntimeError): """Raised when a tool-call span cannot be causally attributed to its requesting gen_ai span.""" @dataclass(frozen=True) class DispatchRecord: trace_id: str parent_span_id: str tool_name: str args_digest: str @dataclass(frozen=True) class ExecutionContext: trace_id: str parent_span_id: str tool_name: str args: dict parent_operation_name: str | None # None => no resolvable parent ambient_span_id: str | None # pool-worker residue; must NOT be trusted GENAI_REASONING_OPS = {"chat", "invoke_agent", "execute_tool"} def digest_args(args: dict) -> str: return hashlib.sha256( json.dumps(args, sort_keys=True, separators=(",", ":")).encode() ).hexdigest() def resolve_attribution(dispatch: DispatchRecord, ctx: ExecutionContext) -> str: # Fail closed: no parent means no attributed child, ever. if not ctx.parent_span_id or ctx.parent_span_id == "0" * 16: raise GenAIAttributionError( f"tool {ctx.tool_name!r} has no parent_span_id; refusing to invent a root" ) # Context bleed: parent resolves into a different trace than the requester claimed. if ctx.trace_id != dispatch.trace_id: raise GenAIAttributionError( f"trace mismatch: dispatch={dispatch.trace_id} exec={ctx.trace_id}; " f"ambient_span={ctx.ambient_span_id} must not be used as parent" ) # Parent exists but is not a gen_ai reasoning operation -> structural lie. if ctx.parent_operation_name not in GENAI_REASONING_OPS: raise GenAIAttributionError( f"parent op {ctx.parent_operation_name!r} is not a gen_ai reasoning op; " "degraded emit required, not attributed child" ) # Stale replay: same span IDs, different arguments. if digest_args(ctx.args) != dispatch.args_digest: raise GenAIAttributionError( f"args_digest mismatch for tool {ctx.tool_name!r}: " "replayed dispatch with mutated inputs; emit degraded, do not attribute" ) return "attributed" def emit_tool_span(dispatch: DispatchRecord, ctx: ExecutionContext) -> dict: try: attribution = resolve_attribution(dispatch, ctx) except GenAIAttributionError as exc: # Degraded path: emit a root span with explicit unresolved attribution. return { "span_name": f"gen_ai.tool.call {ctx.tool_name}", "parent_span_id": None, "gen_ai.tool.call.attribution": "unresolved", "attribution.reason": str(exc), } return { "span_name": f"gen_ai.tool.call {ctx.tool_name}", "parent_span_id": ctx.parent_span_id, "gen_ai.tool.call.attribution": attribution, "gen_ai.tool.name": ctx.tool_name, } ```