# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-tool-call-span-lineage-when-a-model-re-emits-a-tool-call-id-after-a-mid-turn-retry.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-tool-call-span-lineage-when-a-model-re-emits-a-tool-call-id-after-a-mid-turn-retry.warrant.json
# Markdown SHA-256:   bae96aee34df3845a39900044642c9ed27d7448649acaa4ed2a877eee0b106d9
# Code AST SHA-256:   17e281c80086032f1dd5455cb68d53b6e13dd2988af363345f71f15dc2356a7c
# Verified Classes:   ToolCallLineageCollision, ToolSpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ToolCallLineageCollision(RuntimeError):
    """Raised when a tool-call id is reused across distinct model invocations
    within one trace, indicating a retry raced a late-arriving original."""
    pass


@dataclass(frozen=True)
class ToolSpan:
    trace_id: str
    response_id: str          # gen_ai.response.id of the parent chat span
    tool_call_id: str         # gen_ai.tool.call.id
    operation: str            # gen_ai.operation.name
    status: str


def reconcile_tool_lineage(spans: list[ToolSpan]) -> dict[tuple[str, str], ToolSpan]:
    """Group tool-execution spans by (response_id, tool_call_id).

    A collision -- same tool_call_id under two different response_ids in the
    same trace -- means the framework retried a model invocation while the
    original was still in flight, and both produced the same tool_call id.
    That is a duplicate-dispatch condition, not a lookup ambiguity: refuse to
    collapse it silently.
    """
    by_pair: dict[tuple[str, str], ToolSpan] = {}
    by_call_id: dict[str, set[str]] = {}

    for span in spans:
        if span.operation != "execute_tool":
            continue
        pair = (span.response_id, span.tool_call_id)
        by_pair[pair] = span
        by_call_id.setdefault(span.tool_call_id, set()).add(span.response_id)

    for call_id, response_ids in by_call_id.items():
        if len(response_ids) > 1:
            raise ToolCallLineageCollision(
                f"tool_call_id={call_id!r} appears under response_ids="
                f"{sorted(response_ids)} in one trace; a retried model "
                f"invocation reused the call id of a late-arriving original. "
                f"Treat as duplicate dispatch; do not collapse by call id."
            )

    return by_pair
