# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-attributes-as-an-unreliable-correlation-key-across-tool-call-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-attributes-as-an-unreliable-correlation-key-across-tool-call-boundaries.warrant.json
# Markdown SHA-256:   44668fd4f488b1b37be94e2457969be7c88bad1ca945295836fc35353fa2c42b
# Code AST SHA-256:   fee7641bc26c435a4466a684bc091b7a5ce442fa50f5c7f5e946e6d6af0fe9af
# Verified Classes:   UnsoundAttributionError, ToolSpan, ChatSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnsoundAttributionError(RuntimeError):
    """Raised when GenAI span attributes cannot be trusted as a cost-correlation key."""
    pass


@dataclass
class ToolSpan:
    span_id: str
    parent_span_id: str
    tool_call_id: Optional[str]
    tool_name: str
    is_retry: bool = False


@dataclass
class ChatSpan:
    span_id: str
    input_tokens: int
    output_tokens: int
    children: list = field(default_factory=list)


def attribute_cost(chat: ChatSpan, tool_spans: list[ToolSpan]) -> dict[str, float]:
    """
    Distribute a chat span's output tokens across its child tool spans.
    Refuses to use gen_ai.tool.call.id as a join key; uses parent_span_id only.
    """
    children = [t for t in tool_spans if t.parent_span_id == chat.span_id]
    if not children:
        return {}

    # Guard 1: empty tool_call_id means the provider omitted it -> attribute join would collapse.
    if any(t.tool_call_id in (None, "") for t in children):
        raise UnsoundAttributionError(
            f"chat span {chat.span_id}: empty gen_ai.tool.call.id on child tool span; "
            "attribute join is unsound, refusing to attribute"
        )

    # Guard 2: duplicate ids among siblings -> collision, cannot key on attribute.
    ids = [t.tool_call_id.lower() for t in children]
    if len(set(ids)) != len(ids):
        raise UnsoundAttributionError(
            f"chat span {chat.span_id}: duplicate gen_ai.tool.call.id among siblings "
            f"{ids}; attribute join is unsound"
        )

    # Guard 3: retry re-parented under a stale chat span -> double attribution.
    if any(t.is_retry for t in children):
        raise UnsoundAttributionError(
            f"chat span {chat.span_id}: retry child detected; re-parent retries under "
            "the originating chat span before attributing"
        )

    # Sound path: structural distribution across children, id used only as label.
    share = chat.output_tokens / len(children)
    return {t.tool_call_id: share for t in children}
