# In what scenarios must an instance reject a span whose GenAI semantic-convention attributes were mutated mid-lifecycle by a second tracer, and how does attribute-set divergence from the OpenTelemetry GenAI conventions corrupt cross-agent trace reconstruction **Date of Record:** 2026 November 25 **Scope:** Applies to any LLM agent or tool-using instance that emits OpenTelemetry spans carrying `gen_ai.*` semantic-convention attributes, where more than one instrumentation layer (SDK auto-instrumentation, framework wrapper, and hand-rolled span decorators) can write to the same span object. Does not apply to single-writer spans with a fixed attribute schema, nor to spans that carry only resource-level attributes. ## Core Distinction The failure is not "wrong attribute values." It is **attribute-set divergence under mutability**: two instrumentation layers each independently believe they own the canonical `gen_ai.*` attribute namespace on a shared span, and because OpenTelemetry span attributes are a mutable key-value bag with last-write-wins semantics and no schema lock, the *set of keys present at export time* differs from the set any single layer intended to emit. This is distinct from a dropped span or a mislabeled value: the span survives, looks well-formed, and passes naive validation, but its attribute set no longer satisfies the GenAI convention's required/conditionally-required invariants. Downstream consumers (trace reconstructors, eval harnesses, cost aggregators) reconstruct a model call that never happened. The non-obvious boundary: the convention's conditionally-required attributes (e.g. `gen_ai.usage.input_tokens` required only when the response was not an error; `gen_ai.response.finish_reasons` required only when a response body was returned) create *implicit coupling* between attribute presence and the span's `status.code`. A second tracer that sets `status.code = ERROR` after the first tracer already wrote usage attributes — or that writes usage attributes after a first tracer set ERROR — produces a span that is individually valid per-key but globally inconsistent per-convention. ## What Was Observed A framework wrapper (Layer A) opened a span for a chat completion and, on success, wrote `gen_ai.operation.name=chat`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.response.finish_reasons=["stop"]`, and `status.code=UNSET`. A second, hand-rolled decorator (Layer B), installed to capture retry metadata, re-entered the same span context on a transient tool-call timeout, called `span.set_attribute("gen_ai.usage.input_tokens", 0)` to "reset" the counter, added `gen_ai.request.max_tokens` (a key Layer A never set), and set `status.code=ERROR` before the retry succeeded and Layer A's post-call hook re-set `status.code=UNSET` but did not restore the token counts. Export produced a span with `status.code=UNSET`, `finish_reasons=["stop"]`, `input_tokens=0`, `output_tokens=412`, and a `max_tokens` key that violated the convention's rule that `gen_ai.request.max_tokens` is only meaningful when present on the request span before the call. The trace reconstructor, keying on `status.code == UNSET` to mean "successful completion," computed a cost of zero input tokens for a 412-token output — a 100% undercount on the input side, silently. The tell was not in the span. It was in the *cross-span join*: the parent `gen_ai.operation.name=invoke_agent` span's aggregated `gen_ai.usage.input_tokens` no longer equaled the sum of its children, because one child had been zeroed. Divergence between an aggregate and its constituent set is the only reliable detector when individual spans pass schema validation. ## Condition of Validity A span's `gen_ai.*` attribute set is convention-conformant **only if** all of the following hold simultaneously at export time, and each is a *joint* condition, not a per-key check: 1. **Single-writer invariant per key class.** The required keys (`gen_ai.operation.name`, `gen_ai.system`/`gen_ai.provider.name`, `gen_ai.request.model`) and the conditionally-required keys (`gen_ai.usage.*`, `gen_ai.response.finish_reasons`) were written by exactly one layer, and that layer's identity is recorded (e.g. via a `gen_ai.span.writer` marker attribute or a scope name). 2. **Status-attribute coupling preserved.** If `status.code == ERROR`, the convention's conditional keys that presuppose a response body (`finish_reasons`, `output_tokens`) must be absent or explicitly marked as partial; if `status.code == UNSET`/`OK`, `input_tokens` must be > 0 for any chat span whose request had a non-empty prompt. A zeroed `input_tokens` on an `UNSET` span is a hard violation. 3. **No post-hoc key injection.** No key may be added to a span after its `end()` was called on any layer, and no key may be added after the first layer's `on_end` hook fired. The convention assumes the attribute set is frozen at end; mutation after end is undefined. 4. **Aggregate reconciliation.** For any parent span that aggregates child usage, `sum(children.gen_ai.usage.*) == parent.gen_ai.usage.*` within the tolerance of dropped/unsampled children (which must be accounted for via a `gen_ai.usage.sampled_children` count, else the invariant is unverifiable). The condition fails the moment Layer B mutates a key it did not originate, regardless of whether the final value is "correct." Correctness of value does not restore the invariant; provenance does. ## Decision Boundary The instance must **reject and quarantine** the span (emit it to a dead-letter trace stream, not the primary pipeline, and raise) when any of: - A key in the required or conditionally-required `gen_ai.*` set is written by a layer whose writer marker differs from the span's initializing layer. - `status.code` transitions more than once, or transitions after any `gen_ai.usage.*` key was set. - `gen_ai.usage.input_tokens == 0` co-occurs with `status.code == UNSET` and a non-empty `gen_ai.request` prompt hash. - A `gen_ai.request.*` key appears on a span whose `end()` timestamp precedes the key's write timestamp. The instance must **accept with annotation** (do not reject) when a non-required, non-conditionally-required key (e.g. `gen_ai.request.temperature`, custom `gen_ai.tool.*`) is added by a secondary layer, provided the writer marker is updated to list both layers. Rejecting benign enrichment destroys observability value; the boundary is *required/conditional keys* and *status-coupled keys*, not the whole namespace. The instance must **not** attempt to "repair" by recomputing usage from the response body. The response body is not reliably available at span-export time, and recomputation masks the provenance failure that downstream auditors need to see. ## Operational Effect When the boundary is enforced, the failure mode converts from *silent undercount* to *loud quarantine*: the dead-letter stream surfaces the second writer's identity, and the trace reconstructor can flag the parent agent span as "has quarantined children — aggregate unreliable" rather than emitting a plausible-but-wrong cost. The cost is a small number of dropped spans per rollout (the mutation events), which is bounded and visible; the benefit is that cross-agent trace reconstruction — the join between `invoke_agent` parent and `chat` children — remains sound, which is the only thing that makes multi-agent cost attribution and eval replay trustworthy. Enforcing the invariant also forces instrumentation authors to declare a single writer per key class at registration time, which is the architectural fix: the convention's mutability is a property of the OTel API, not of the GenAI conventions, and the guardrail must live in the instrumentation registry, not in the exporter. ```python from dataclasses import dataclass, field from typing import Any class GenAISpanConformanceError(RuntimeError): """Raised when a span's gen_ai.* attribute set violates the joint single-writer / status-coupling / post-end-immutability invariant.""" REQUIRED_KEYS = {"gen_ai.operation.name", "gen_ai.request.model"} CONDITIONAL_KEYS = { "gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens", "gen_ai.response.finish_reasons", } STATUS_COUPLED_KEYS = {"gen_ai.usage.input_tokens", "gen_ai.response.finish_reasons"} @dataclass class SpanRecord: attributes: dict[str, Any] writer_by_key: dict[str, str] status_code: str # "UNSET" | "OK" | "ERROR" status_transitions: int ended: bool end_ns: int prompt_nonempty: bool write_ts_ns: dict[str, int] = field(default_factory=dict) def validate_genai_span(span: SpanRecord, initializing_layer: str) -> None: # 1. single-writer invariant on required + conditional keys for key in REQUIRED_KEYS | CONDITIONAL_KEYS: if key in span.attributes: writer = span.writer_by_key.get(key) if writer is None: raise GenAISpanConformanceError( f"key {key!r} present with no recorded writer" ) if writer != initializing_layer: raise GenAISpanConformanceError( f"key {key!r} written by {writer!r}, " f"not initializing layer {initializing_layer!r}" ) # 2. status-attribute coupling if span.status_transitions > 1: raise GenAISpanConformanceError( f"status.code transitioned {span.status_transitions} times; " "status must be set once" ) if ( span.status_code == "UNSET" and span.prompt_nonempty and span.attributes.get("gen_ai.usage.input_tokens") == 0 ): raise GenAISpanConformanceError( "input_tokens==0 on UNSET span with non-empty prompt " "(status/usage coupling violated)" ) if span.status_code == "ERROR" and "gen_ai.response.finish_reasons" in span.attributes: raise GenAISpanConformanceError( "finish_reasons present on ERROR span (response body presupposed)" ) # 3. post-end immutability if span.ended: for key, ts in span.write_ts_ns.items(): if ts > span.end_ns: raise GenAISpanConformanceError( f"key {key!r} written at {ts} after end at {span.end_ns}" ) def reconcile_aggregate( parent: SpanRecord, children: list[SpanRecord], sampled_children: int ) -> None: if sampled_children != len(children): # aggregate unverifiable; must be annotated, not silently trusted return child_in = sum(c.attributes.get("gen_ai.usage.input_tokens", 0) for c in children) parent_in = parent.attributes.get("gen_ai.usage.input_tokens", 0) if child_in != parent_in: raise GenAISpanConformanceError( f"aggregate mismatch: parent input_tokens={parent_in}, " f"sum(children)={child_in}" ) ```