# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-spans-before-its-tool-call-attributes-are-finalized-the-attribute-mutation-after-export-race-in-opentelemetr.md # Remnant Warrant: https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-spans-before-its-tool-call-attributes-are-finalized-the-attribute-mutation-after-export-race-in-opentelemetr.warrant.json # Markdown SHA-256: bd29856ac4ffb1c33fe7f8907fc61cf50da3bf4aba99dad2852160430d54710f # Code AST SHA-256: b5e08ac99c82a757dd9e8c9b0bb56fec77c8e86fe1ce5b558c427f36cbc65f76 # Verified Classes: GenAIAttributeRaceError, GenAISpan # Defensive Guards: 5 fail-closed invariants (zero external deps) # Governance: Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com) from __future__ import annotations import json import threading from dataclasses import dataclass, field from typing import Any class GenAIAttributeRaceError(RuntimeError): """Raised when a gen_ai.* span attribute is mutated after the span has been handed to the export path, or when token accounting is attached to a span that is not the terminal model-invocation span.""" @dataclass class GenAISpan: name: str span_id: str attributes: dict[str, Any] = field(default_factory=dict) _lock: threading.Lock = field(default_factory=threading.Lock, repr=False) _exported: bool = False _ended: bool = False def set_attribute(self, key: str, value: Any) -> None: if not key.startswith("gen_ai."): # Non-GenAI attributes are out of scope for this guardrail. with self._lock: self.attributes[key] = value return with self._lock: if self._exported: raise GenAIAttributeRaceError( f"attribute {key!r} set on span {self.span_id!r} after export; " "the exported payload will not reflect this value" ) self.attributes[key] = value def set_tool_arguments(self, raw_json: str) -> None: # Enforce validity: tool-call arguments must be fully assembled JSON, # never a streamed fragment. try: json.loads(raw_json) except json.JSONDecodeError as exc: raise GenAIAttributeRaceError( f"gen_ai.tool.call.arguments on span {self.span_id!r} is not " f"valid JSON (likely a streamed fragment): {exc}" ) from exc self.set_attribute("gen_ai.tool.call.arguments", raw_json) def set_usage(self, input_tokens: int, output_tokens: int) -> None: if self.name != "gen_ai.chat": raise GenAIAttributeRaceError( f"gen_ai.usage.* set on span {self.span_id!r} of type " f"{self.name!r}; token accounting must live on the terminal " "gen_ai.chat span only" ) with self._lock: if "gen_ai.usage.input_tokens" in self.attributes: raise GenAIAttributeRaceError( f"gen_ai.usage.* set twice on span {self.span_id!r}; " "retry child spans must not re-attribute usage" ) self.attributes["gen_ai.usage.input_tokens"] = input_tokens self.attributes["gen_ai.usage.output_tokens"] = output_tokens def export_snapshot(self) -> dict[str, Any]: # Called by the batch processor. Must be the only path that flips # _exported, and must hold the lock while reading. with self._lock: self._exported = True return {"name": self.name, "span_id": self.span_id, "attributes": dict(self.attributes)} def end(self) -> None: with self._lock: if self._ended: raise GenAIAttributeRaceError( f"span {self.span_id!r} ended twice" ) self._ended = True def finalize_tool_span(span: GenAISpan, raw_arguments: str, result: str) -> dict[str, Any]: """Set all terminal attributes atomically, then export. This is the invariant-preserving path: no mutation after export is possible because export happens last, under the span lock.""" span.set_tool_arguments(raw_arguments) span.set_attribute("gen_ai.tool.call.result", result) span.end() return span.export_snapshot()