# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-span-attributes-from-silently-desynchronizing-tool-call-identity-across-agent-turns.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-span-attributes-from-silently-desynchronizing-tool-call-identity-across-agent-turns.warrant.json
# Markdown SHA-256:   638d8c512a9491069b2c284cafbbdb5648789df73f89d53ae2eceab32bf06b9d
# Code AST SHA-256:   c6f791258ed3f6d3ef6827b9b8da1d5ef3e2ccf430943f021b6499d91ee1a846
# Verified Classes:   CorrelationInvariantError, ToolSpan, ModelToolRequest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class CorrelationInvariantError(RuntimeError):
    """Raised when a GenAI span's correlation attributes violate a load-bearing invariant."""


@dataclass(frozen=True)
class ToolSpan:
    tool_call_id: str          # gen_ai.tool.call.id
    agent_turn: int            # gen_ai.agent.turn, captured at span start
    tool_name: str             # gen_ai.tool.name


@dataclass(frozen=True)
class ModelToolRequest:
    tool_call_id: str          # tool_call_id from the assistant message
    agent_turn: int


def emit_execute_tool_span(
    request: ModelToolRequest,
    *,
    executor_minted_id: str | None,
    span_turn_at_close: int,
) -> ToolSpan:
    """Emit an execute_tool span, enforcing ID provenance and turn binding.

    The executor MUST NOT mint its own ID; it must echo the model's tool_call_id.
    The turn MUST be captured at span start, not read at close.
    """
    if executor_minted_id is not None and executor_minted_id != request.tool_call_id:
        raise CorrelationInvariantError(
            f"tool_call_id provenance violated: model emitted {request.tool_call_id!r}, "
            f"executor minted {executor_minted_id!r}; join will silently fail."
        )
    if span_turn_at_close != request.agent_turn:
        raise CorrelationInvariantError(
            f"agent_turn skew: span closed at turn {span_turn_at_close}, "
            f"request bound to turn {request.agent_turn}; cost attribution will mis-bucket."
        )
    return ToolSpan(
        tool_call_id=request.tool_call_id,
        agent_turn=request.agent_turn,
        tool_name="",  # populated by caller
    )


def verify_trace_correlation(
    requests: list[ModelToolRequest], spans: list[ToolSpan]
) -> None:
    """Auditor-side check: a short join is an error, not a fallback trigger."""
    span_ids = {s.tool_call_id for s in spans}
    missing = [r.tool_call_id for r in requests if r.tool_call_id not in span_ids]
    if missing:
        raise CorrelationInvariantError(
            f"trace unverifiable: {len(missing)} tool requests have no matching span "
            f"(ids={missing[:3]}...); refusing positional fallback."
        )
    for r, s in zip(sorted(requests, key=lambda x: x.tool_call_id),
                    sorted(spans, key=lambda x: x.tool_call_id)):
        if r.agent_turn != s.agent_turn:
            raise CorrelationInvariantError(
                f"turn mismatch on {r.tool_call_id}: request turn {r.agent_turn} "
                f"vs span turn {s.agent_turn}"
            )
