# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-emit-a-duplicate-gen-ai-tool-call-id-span-after-mcp-handoff-but-the-parent-trace-shows-a-single-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-emit-a-duplicate-gen-ai-tool-call-id-span-after-mcp-handoff-but-the-parent-trace-shows-a-single-invocation.warrant.json
# Markdown SHA-256:   5808bc1de904e3b1ff0b15a6ee46095e27417cd4d4ed13149147a7f51db17cab
# Code AST SHA-256:   7ad40dd15689b5eb5649bf4b42f197f764b0c9ed63526b0f3a546f50517df8ab
# Verified Classes:   DuplicateToolCallIdError, ToolCallSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import re
from dataclasses import dataclass
from typing import Iterable


class DuplicateToolCallIdError(RuntimeError):
    """Raised when a trace contains collided gen_ai.tool.call.id values
    with contradictory terminal statuses and no retry marker."""


@dataclass(frozen=True)
class ToolCallSpan:
    trace_id: str
    span_id: str
    tool_call_id: str
    status: str  # "OK" | "ERROR" | "UNSET"
    error_type: str | None
    retry_count: int | None
    result_present: bool


_ID_PATTERN = re.compile(r"^[0-9a-f]{32}:[0-9a-f]{16}$")


def validate_tool_call_ids(spans: Iterable[ToolCallSpan]) -> None:
    """Enforce: one gen_ai.tool.call.id => one execution, or an explicit retry marker."""
    by_id: dict[str, list[ToolCallSpan]] = {}
    for span in spans:
        by_id.setdefault(span.tool_call_id, []).append(span)

    for call_id, group in by_id.items():
        # Invariant 1: id must be derived from span context, not minted locally.
        if not _ID_PATTERN.match(call_id):
            raise DuplicateToolCallIdError(
                f"gen_ai.tool.call.id={call_id!r} is not of form "
                f"'<trace_id>:<span_id>'; it was minted from local state and "
                f"cannot be safely joined across handoffs."
            )

        statuses = {s.status for s in group}
        retry_marked = any((s.retry_count or 0) > 0 for s in group)

        # Invariant 2: OK and ERROR under one id require an explicit retry marker.
        if "OK" in statuses and "ERROR" in statuses and not retry_marked:
            raise DuplicateToolCallIdError(
                f"gen_ai.tool.call.id={call_id!r} has both OK and ERROR spans "
                f"without gen_ai.tool.call.retry.count; this is the signature "
                f"of a non-propagated retry after MCP handoff. "
                f"Spans: {[(s.span_id, s.status, s.error_type) for s in group]}"
            )

        # Invariant 3: at most one terminal OK per id (retries must be marked).
        ok_spans = [s for s in group if s.status == "OK"]
        if len(ok_spans) > 1 and not retry_marked:
            raise DuplicateToolCallIdError(
                f"gen_ai.tool.call.id={call_id!r} has {len(ok_spans)} OK spans "
                f"but no retry marker; tool executed more than once under one id."
            )


def ingest(spans: list[ToolCallSpan]) -> None:
    validate_tool_call_ids(spans)
    # downstream: emit to collector, attribute cost, feed eval harness
