# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-attributes-before-export-and-why-the-tool-call-attribute-contract-fractures-at-the-span-clos.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-attributes-before-export-and-why-the-tool-call-attribute-contract-fractures-at-the-span-clos.warrant.json
# Markdown SHA-256:   3090d072bb195dd109b36f4b2497795a376b2a5cff89fa4da0534b272e72fe2e
# Code AST SHA-256:   20f6b6765e0dbee97c2d4453081b0d1f37160c537dba8e1779cfc971b2555a70
# Verified Classes:   GenAISpanContractError, TurnContext, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import copy
from dataclasses import dataclass, field
from typing import Any


class GenAISpanContractError(RuntimeError):
    """Raised when a GenAI span's attributes violate the finalize-before-export invariant."""
    pass


@dataclass
class TurnContext:
    # Mutable, reused across turns; the compaction routine zeroes these in place.
    tool_call_id: str = ""
    input_tokens: int = 0
    output_tokens: int = 0
    tool_name: str = ""


@dataclass
class GenAISpan:
    name: str
    attributes: dict[str, Any] = field(default_factory=dict)
    _finalized: bool = False

    def set_attribute(self, key: str, value: Any) -> None:
        if self._finalized:
            raise GenAISpanContractError(
                f"attribute {key!r} set after finalize on span {self.name!r}"
            )
        self.attributes[key] = value

    def finalize(self, ctx: TurnContext) -> None:
        """Deep-snapshot live counters into the span's own immutable dict."""
        snapshot = {
            "gen_ai.tool.name": ctx.tool_name,
            "gen_ai.tool.call.id": ctx.tool_call_id,
            "gen_ai.usage.input_tokens": ctx.input_tokens,
            "gen_ai.usage.output_tokens": ctx.output_tokens,
        }
        self.attributes.update(copy.deepcopy(snapshot))
        # Detach: the span no longer aliases the mutable turn context.
        self._finalized = True

    def validate(self) -> None:
        if not self._finalized:
            raise GenAISpanContractError(
                f"span {self.name!r} exported without finalize(); attributes may alias live state"
            )
        name = self.attributes.get("gen_ai.tool.name", "")
        call_id = self.attributes.get("gen_ai.tool.call.id", "")
        in_tok = self.attributes.get("gen_ai.usage.input_tokens", 0)
        if name and not call_id:
            raise GenAISpanContractError(
                f"span {self.name!r} has tool name {name!r} but empty call id; "
                "trace join will break and cost attribution will undercount"
            )
        if name and in_tok == 0:
            raise GenAISpanContractError(
                f"span {self.name!r} reports zero input tokens for a completed tool call; "
                "likely counter reset during compaction"
            )


def export_span(span: GenAISpan) -> dict[str, Any]:
    span.validate()
    return {"name": span.name, "attributes": dict(span.attributes)}


# Reproduction of the observed failure:
ctx = TurnContext(tool_call_id="call_a1", input_tokens=812, tool_name="search")
span = GenAISpan(name="gen_ai.tool.call")
span.set_attribute("gen_ai.tool.name", "search")
span.finalize(ctx)          # correct path: snapshot taken here
ctx.tool_call_id = ""       # compaction reuses the dict in place
ctx.input_tokens = 0
export_span(span)           # passes: snapshot is detached from ctx

# Failure path: span closed without finalize, then compaction mutates ctx.
bad = GenAISpan(name="gen_ai.tool.call")
bad.set_attribute("gen_ai.tool.name", "search")
bad.set_attribute("gen_ai.tool.call.id", ctx.tool_call_id)  # aliases live value
ctx.tool_call_id = ""       # compaction zeroes it
ctx.input_tokens = 0
try:
    export_span(bad)        # raises GenAISpanContractError
except GenAISpanContractError as e:
    print(f"blocked corrupt export: {e}")
