# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-span-attribute-collapse-when-opentelemetry-genai-tool-call-spans-are-emitted-from-a-retried-or-re-entrant-agent-step.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-span-attribute-collapse-when-opentelemetry-genai-tool-call-spans-are-emitted-from-a-retried-or-re-entrant-agent-step.warrant.json
# Markdown SHA-256:   a4720da0883f675d8a75abf2e55c3cbf5bcd38095fa9972fbc49bb5efa09eab2
# Code AST SHA-256:   5502b7bf5b8c104c85257139e7fb88f8c694225b2185b2b825a4d73f4ef22e20
# Verified Classes:   SpanAttributeCollapseError, GenAISpan, SpanIdentityGuard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class SpanAttributeCollapseError(RuntimeError):
    """Raised when a GenAI tool-call span would overwrite a prior execution's attributes."""


@dataclass
class GenAISpan:
    trace_id: str
    span_id: str
    call_id: str            # gen_ai.tool.call.id
    attempt: int            # gen_ai.tool.call.attempt (1-based)
    tool_name: str          # gen_ai.tool.name
    input_tokens: int       # gen_ai.usage.input_tokens
    output_tokens: int      # gen_ai.usage.output_tokens
    status_code: str        # status.code
    links: list[str] = field(default_factory=list)  # span_ids of prior closed spans


class SpanIdentityGuard:
    """Enforces attribute-per-execution uniqueness at the exporter boundary."""

    def __init__(self) -> None:
        self._emitted_keys: set[tuple[str, str, int]] = set()
        self._closed_span_ids: dict[str, str] = {}  # span_id -> trace_id

    def close(self, span: GenAISpan) -> None:
        self._closed_span_ids[span.span_id] = span.trace_id

    def emit(self, span: GenAISpan) -> None:
        key = (span.trace_id, span.call_id, span.attempt)
        if key in self._emitted_keys:
            raise SpanAttributeCollapseError(
                f"duplicate execution key {key}: attempt {span.attempt} of "
                f"call {span.call_id} already emitted; a retry must carry a "
                f"fresh attempt discriminator, not reuse the prior span's identity"
            )
        # A resumed step must link to the closed span, never re-emit its span_id.
        if span.span_id in self._closed_span_ids:
            if span.span_id not in span.links:
                raise SpanAttributeCollapseError(
                    f"span_id {span.span_id} already closed in trace "
                    f"{self._closed_span_ids[span.span_id]}; re-emission after "
                    f"checkpoint resume requires a Span Link, not identity reuse"
                )
        self._emitted_keys.add(key)
        self.close(span)


def replay_retry_sequence(guard: SpanIdentityGuard) -> None:
    first = GenAISpan(
        trace_id="t-1", span_id="s-1", call_id="call_7f3a", attempt=1,
        tool_name="search_documents", input_tokens=812, output_tokens=0,
        status_code="ERROR",
    )
    guard.emit(first)

    # The buggy path: retry re-uses the same attempt number and span_id.
    retry_buggy = GenAISpan(
        trace_id="t-1", span_id="s-1", call_id="call_7f3a", attempt=1,
        tool_name="search_documents", input_tokens=812, output_tokens=214,
        status_code="OK",
    )
    guard.emit(retry_buggy)  # raises SpanAttributeCollapseError
