# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-otel-genai-agent-spans-from-silently-collapsing-retried-tool-calls-into-a-single-logical-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-otel-genai-agent-spans-from-silently-collapsing-retried-tool-calls-into-a-single-logical-invocation.warrant.json
# Markdown SHA-256:   e18d7b4afd8927966f8a52550110a529c3fea7875609b4e470579b890d774a6b
# Code AST SHA-256:   bc334665cf684fb5afe45a413ee149a13556b238537fb04b46f4fbd4e39ccee2
# Verified Classes:   GenAiSpanIdentityCollision
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class GenAiSpanIdentityCollision(RuntimeError):
    """Raised when two execute_tool spans in one trace share gen_ai.tool.call.id."""
    pass


def mint_tool_attempt_identity(
    model_call_id: str,
    invocation_seq: int,
    attempt_seq: int,
) -> dict:
    """
    Build the identity attributes for an execute_tool span.

    model_call_id : the ID the model serialized into its tool-call payload
    invocation_seq: logical invocation counter for this model turn (0-based)
    attempt_seq   : retry attempt counter within the invocation (0-based)

    Invariant: gen_ai.tool.call.id is attempt-scoped and unique per span;
    gen_ai.tool.invocation.id is stable across retries of the same intent.
    """
    if not model_call_id:
        raise GenAiSpanIdentityCollision(
            "model_call_id is empty; cannot derive attempt identity"
        )
    if attempt_seq < 0 or invocation_seq < 0:
        raise GenAiSpanIdentityCollision(
            f"negative sequence: invocation={invocation_seq} attempt={attempt_seq}"
        )

    invocation_id = f"{model_call_id}:inv{invocation_seq}"
    call_id = f"{invocation_id}:att{attempt_seq}"
    return {
        "gen_ai.tool.call.id": call_id,
        "gen_ai.tool.invocation.id": invocation_id,
        "gen_ai.tool.attempt": attempt_seq,
    }


def assert_no_call_id_collision(spans: list[dict]) -> None:
    """
    Enforce the per-trace uniqueness invariant before export.
    Called by the span processor; a collision must fail loudly, not aggregate.
    """
    seen: dict[tuple[str, str], int] = {}
    for span in spans:
        attrs = span.get("attributes", {})
        call_id = attrs.get("gen_ai.tool.call.id")
        if call_id is None:
            continue
        key = (span.get("trace_id", ""), call_id)
        if key in seen:
            raise GenAiSpanIdentityCollision(
                f"duplicate gen_ai.tool.call.id={call_id!r} in "
                f"trace={span.get('trace_id')!r}; attempt-scoped IDs required"
            )
        seen[key] = 1
