# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-genai-tool-call-span-the-gen-ai-tool-call-id-tool-call-id-correlation-invariant-under-retried-tool-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-genai-tool-call-span-the-gen-ai-tool-call-id-tool-call-id-correlation-invariant-under-retried-tool-execution.warrant.json
# Markdown SHA-256:   b3e31a99b1a1e821d62aba1ce066019d267a015d02520befd3eecc95d98fed1b
# Code AST SHA-256:   03ca6d26da0b606c961420bf3cc6c8e41d31a11071e7b63eb48a6ed4e6288daa
# Verified Classes:   ToolCallIdentityCollision, SpanRecord, TraceSpanIndex
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ToolCallIdentityCollision(RuntimeError):
    """Raised when two exported spans in one trace claim the same gen_ai.tool.call.id."""


@dataclass
class SpanRecord:
    trace_id: str
    span_id: str
    gen_ai_tool_call_id: str | None
    retry_attempt: int = 0
    status: str = "OK"


@dataclass
class TraceSpanIndex:
    _seen: dict[tuple[str, str], str] = field(default_factory=dict)

    def admit(self, span: SpanRecord) -> None:
        if span.gen_ai_tool_call_id is None:
            return  # retry/speculation spans must not claim the logical id
        key = (span.trace_id, span.gen_ai_tool_call_id)
        if key in self._seen:
            raise ToolCallIdentityCollision(
                f"trace {span.trace_id}: gen_ai.tool.call.id "
                f"{span.gen_ai_tool_call_id!r} already claimed by span "
                f"{self._seen[key]!r}; retry attempt {span.retry_attempt} "
                f"must omit the id and link to the terminal span instead"
            )
        self._seen[key] = span.span_id


def emit_retry_span(
    index: TraceSpanIndex,
    trace_id: str,
    span_id: str,
    logical_call_id: str,
    attempt: int,
    idempotent: bool,
) -> SpanRecord:
    if not idempotent:
        # Non-idempotent retries are distinct logical calls; the orchestrator
        # must mint a new tool_call_id rather than reuse this one.
        raise ToolCallIdentityCollision(
            f"refusing to retry non-idempotent call {logical_call_id!r} "
            f"under the same gen_ai.tool.call.id (attempt {attempt})"
        )
    span = SpanRecord(
        trace_id=trace_id,
        span_id=span_id,
        gen_ai_tool_call_id=None,  # retry spans never claim the logical id
        retry_attempt=attempt,
        status="ERROR",
    )
    index.admit(span)
    return span


def emit_terminal_span(
    index: TraceSpanIndex,
    trace_id: str,
    span_id: str,
    logical_call_id: str,
    attempt: int,
) -> SpanRecord:
    span = SpanRecord(
        trace_id=trace_id,
        span_id=span_id,
        gen_ai_tool_call_id=logical_call_id,
        retry_attempt=attempt,
        status="OK",
    )
    index.admit(span)  # raises ToolCallIdentityCollision on duplicate
    return span
