# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-tool-call-span-attribute-collapse-under-opentelemetry-genai-semantic-conventions-when-a-single-logical-tool-invocatio.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-tool-call-span-attribute-collapse-under-opentelemetry-genai-semantic-conventions-when-a-single-logical-tool-invocatio.warrant.json
# Markdown SHA-256:   70bafae59defcf269d1f6388af92927be3e0aeea882c1261d7ee8e3c7f333da2
# Code AST SHA-256:   261ae2ed533a42d98b5263138cff431e95662d436bbb150c0798ccee79fdc238
# Verified Classes:   ToolCallAccountingCollapse
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ToolCallAccountingCollapse(RuntimeError):
    """Raised when GenAI tool-call spans violate the invocation/attempt identity invariant."""
    pass


def validate_tool_call_spans(spans: list[dict]) -> None:
    """
    Enforce: within a (conversation_id, tool.name) group, either
      - call IDs are unique per attempt AND a shared invocation id groups them, or
      - a single call ID is reused AND an attempt discriminator is present.
    Anything else is a silent accounting collapse.
    """
    groups: dict[tuple[str, str], list[dict]] = {}
    for s in spans:
        if s.get("gen_ai.operation.name") != "execute_tool":
            continue
        key = (s.get("gen_ai.conversation.id"), s.get("gen_ai.tool.name"))
        groups.setdefault(key, []).append(s)

    for (conv, tool), members in groups.items():
        call_ids = [m.get("gen_ai.tool.call.id") for m in members]
        invocation_ids = {m.get("agent.tool.invocation.id") for m in members}
        attempts = {m.get("agent.tool.attempt") for m in members}

        unique_call_ids = len(set(call_ids)) == len(call_ids)
        shared_invocation = len(invocation_ids) == 1 and None not in invocation_ids
        reuse_with_attempts = len(set(call_ids)) == 1 and None not in attempts

        if unique_call_ids and shared_invocation:
            continue
        if reuse_with_attempts:
            continue

        raise ToolCallAccountingCollapse(
            f"Invocation/attempt identity invariant violated for "
            f"conversation={conv!r} tool={tool!r}: "
            f"call_ids={call_ids}, invocation_ids={invocation_ids}, attempts={attempts}. "
            f"Token sums and retry rates over this group are unreliable."
        )
