# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-span-attribute-coverage-gaps-from-silently-erasing-tool-call-causality-in-opentelemetry-genai-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-span-attribute-coverage-gaps-from-silently-erasing-tool-call-causality-in-opentelemetry-genai-traces.warrant.json
# Markdown SHA-256:   2f577017c2d6a136b75b4e0e0f75d0c1729f2d7cdfae87c6d38aa236ce680c5a
# Code AST SHA-256:   e16aadd93b162e191afe931d8e1a2a6280172ce656d4c3214b62e7e1981e0b6b
# Verified Classes:   ToolCallCorrelationError, ModelToolRequest, ToolSpanAttrs
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ToolCallCorrelationError(RuntimeError):
    """Raised when a tool span cannot be causally linked to its requesting model turn."""
    pass


@dataclass
class ModelToolRequest:
    provider_call_id: str          # e.g. "call_abc123" from the model response
    tool_name: str
    arguments: dict


@dataclass
class ToolSpanAttrs:
    gen_ai_tool_name: str
    gen_ai_tool_call_id: str
    parent_span_id: str


def build_tool_span_attrs(
    request: ModelToolRequest,
    dispatcher_generated_id: Optional[str],
    parent_span_id: str,
) -> ToolSpanAttrs:
    # Invariant: the correlation key must be single-sourced from the model
    # response. A dispatcher-minted ID is never an acceptable substitute.
    if not request.provider_call_id:
        raise ToolCallCorrelationError(
            f"model tool request for '{request.tool_name}' has no provider_call_id; "
            "cannot emit causally linkable span"
        )

    if dispatcher_generated_id is not None and dispatcher_generated_id != request.provider_call_id:
        raise ToolCallCorrelationError(
            "correlation key divergence: dispatcher id "
            f"{dispatcher_generated_id!r} != provider id {request.provider_call_id!r} "
            f"for tool '{request.tool_name}'. Refusing to emit orphaned span."
        )

    if not parent_span_id:
        raise ToolCallCorrelationError(
            "missing parent span id: context propagation across dispatcher "
            "boundary was lost; tool span would become a trace root"
        )

    return ToolSpanAttrs(
        gen_ai_tool_name=request.tool_name,
        gen_ai_tool_call_id=request.provider_call_id,
        parent_span_id=parent_span_id,
    )


def assert_bidirectional_link(
    chat_response_call_ids: list[str],
    emitted_tool_span_call_ids: list[str],
) -> None:
    requested = set(chat_response_call_ids)
    emitted = set(emitted_tool_span_call_ids)
    missing = requested - emitted
    orphaned = emitted - requested
    if missing or orphaned:
        raise ToolCallCorrelationError(
            f"causality edge incomplete: missing={sorted(missing)} "
            f"orphaned={sorted(orphaned)}"
        )
