# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-emit-a-genai-span-after-a-tool-call-attribute-mutation-or-the-parent-child-orphan-invariant-in-opentelemetry-agent-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-emit-a-genai-span-after-a-tool-call-attribute-mutation-or-the-parent-child-orphan-invariant-in-opentelemetry-agent-traces.warrant.json
# Markdown SHA-256:   400fe8dbbb066feadc271738948c66dfa49d90fb5f8a54f7321f8d335549cad3
# Code AST SHA-256:   3b7828c226d831237e4ed552d7ce8d560e06299e34607a0bcf7b28115f0f87cd
# Verified Classes:   GenAISpanParentInvariantError, GenAISpan
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class GenAISpanParentInvariantError(RuntimeError):
    """Raised when a tool-call span's parent linkage violates the GenAI
    semantic-convention invariant (tool-call parent must be the issuing
    gen_ai.chat span, and identity attributes must be fixed at creation)."""


@dataclass
class GenAISpan:
    span_id: str
    parent_span_id: Optional[str]
    operation: str
    attributes: dict = field(default_factory=dict)
    _identity_attrs: frozenset = frozenset(
        {"gen_ai.tool.call.id", "gen_ai.operation.name", "gen_ai.tool.parent_chat_span_id"}
    )
    _exported: bool = False

    def set_attribute(self, key: str, value) -> None:
        if self._exported:
            raise GenAISpanParentInvariantError(
                f"span {self.span_id} already exported; attribute {key} mutation "
                f"cannot affect assembled trace"
            )
        if key in self._identity_attrs and key in self.attributes:
            raise GenAISpanParentInvariantError(
                f"identity attribute {key} on span {self.span_id} is immutable-once-set; "
                f"re-emit with fresh span_id instead of overwriting"
            )
        self.attributes[key] = value

    def end_and_export(self) -> None:
        self._exported = True


def open_tool_call_span(
    chat_span: GenAISpan,
    tool_name: str,
    tool_call_id: str,
    new_span_id: str,
) -> GenAISpan:
    if chat_span.operation != "gen_ai.chat":
        raise GenAISpanParentInvariantError(
            f"tool-call parent must be gen_ai.chat, got {chat_span.operation}"
        )
    if chat_span._exported:
        raise GenAISpanParentInvariantError(
            f"cannot parent tool-call to already-exported chat span {chat_span.span_id}"
        )
    span = GenAISpan(
        span_id=new_span_id,
        parent_span_id=chat_span.span_id,
        operation="gen_ai.tool.call",
    )
    span.set_attribute("gen_ai.tool.name", tool_name)
    span.set_attribute("gen_ai.tool.call.id", tool_call_id)
    return span


def validate_exported_trace(spans: list) -> None:
    by_id = {s.span_id: s for s in spans}
    for s in spans:
        if s.operation == "gen_ai.tool.call":
            parent = by_id.get(s.parent_span_id)
            if parent is None:
                raise GenAISpanParentInvariantError(
                    f"tool-call span {s.span_id} has dangling parent {s.parent_span_id}"
                )
            if parent.operation != "gen_ai.chat":
                raise GenAISpanParentInvariantError(
                    f"tool-call span {s.span_id} parented to {parent.operation} "
                    f"({parent.span_id}); violates GenAI parent-linkage invariant"
                )
