# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-span-attribute-corruption-when-opentelemetry-genai-semantic-conventions-are-emitted-mid-loop-by-an-agent-that-mutates-its-own.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-span-attribute-corruption-when-opentelemetry-genai-semantic-conventions-are-emitted-mid-loop-by-an-agent-that-mutates-its-own.warrant.json
# Markdown SHA-256:   f41c502cd6f30d1d1b989952270f8f3ae3ddda79bfeadc2602f072c6068dc1b5
# Code AST SHA-256:   8da3c52abbda16f5a0c531a3f1aaff61376947dd0f1f4e315cb1d5bf8f64ffb7
# Verified Classes:   AttributionClosureViolation, GenAISpan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class AttributionClosureViolation(RuntimeError):
    """Raised when a span's GenAI attribution tuple mutates mid-lifetime."""
    pass


@dataclass
class GenAISpan:
    span_id: str
    operation_name: str
    request_model: str
    tool_name: Optional[str] = None
    tool_call_id: Optional[str] = None
    tool_schema_hash: Optional[str] = None
    output_tokens: int = 0
    closed: bool = False
    _per_model_tokens: dict = field(default_factory=dict)

    def _attribution_tuple(self):
        return (
            self.request_model,
            self.tool_name,
            self.tool_call_id,
            self.tool_schema_hash,
        )

    def add_tokens(self, model: str, n: int) -> None:
        if self.closed:
            raise AttributionClosureViolation(
                f"span {self.span_id} closed; cannot add tokens"
            )
        if model != self.request_model:
            # C1: a token contribution from a different model must not be
            # folded into a span pinned to request_model.
            raise AttributionClosureViolation(
                f"span {self.span_id} pinned to {self.request_model!r} "
                f"received tokens from {model!r}; close-and-reopen required"
            )
        self.output_tokens += n
        self._per_model_tokens[model] = self._per_model_tokens.get(model, 0) + n

    def mutate_tool(self, new_name: str, new_schema: dict) -> None:
        new_hash = hashlib.sha256(
            repr(sorted(new_schema.items())).encode()
        ).hexdigest()[:12]
        if self.closed:
            raise AttributionClosureViolation(
                f"span {self.span_id} closed; cannot mutate tool identity"
            )
        if self.tool_schema_hash is not None and new_hash != self.tool_schema_hash:
            # C2: schema change under a stable tool name / call id is an
            # attribution-relevant mutation. Must mint a new call id + span.
            raise AttributionClosureViolation(
                f"span {self.span_id} tool {self.tool_name!r} schema changed "
                f"{self.tool_schema_hash!r} -> {new_hash!r}; "
                f"retry must mint new gen_ai.tool.call.id and new span"
            )
        self.tool_name = new_name
        self.tool_schema_hash = new_hash

    def close(self) -> dict:
        self.closed = True
        return {
            "span_id": self.span_id,
            "gen_ai.operation.name": self.operation_name,
            "gen_ai.request.model": self.request_model,
            "gen_ai.response.model": self.request_model,
            "gen_ai.usage.output_tokens": self.output_tokens,
            "gen_ai.tool.name": self.tool_name,
            "gen_ai.tool.call.id": self.tool_call_id,
            "_per_model_tokens": dict(self._per_model_tokens),
        }


def reconcile(parent: dict, children: list[dict]) -> None:
    """Enforce C3: parent token total must equal sum of children, per model."""
    child_by_model: dict = {}
    for c in children:
        for m, n in c["_per_model_tokens"].items():
            child_by_model[m] = child_by_model.get(m, 0) + n
    parent_by_model = parent["_per_model_tokens"]
    if child_by_model != parent_by_model:
        raise AttributionClosureViolation(
            f"span {parent['span_id']} token attribution non-additive: "
            f"parent={parent_by_model} children={child_by_model}"
        )
