# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-an-opentelemetry-genai-span-as-non-authoritative-when-tool-call-events-and-model-invocation-attributes-d.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-an-opentelemetry-genai-span-as-non-authoritative-when-tool-call-events-and-model-invocation-attributes-d.warrant.json
# Markdown SHA-256:   9a03f855fc66e37c473bb95da5d2575ce62e88515875a6f646de56b5da62246f
# Code AST SHA-256:   a3333d9f7da8fa72c2e343042eb20976cb629f99c7734bf8994511ded21070f8
# Verified Classes:   TraceOrderAmbiguousError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class TraceOrderAmbiguousError(RuntimeError):
    """Raised when a GenAI trace cannot be reconciled to a single turn order."""


@dataclass(frozen=True)
class Span:
    operation: str                 # "chat" | "execute_tool"
    start_unix_nano: int
    tool_call_id: str | None = None          # set on execute_tool spans
    referenced_call_ids: frozenset[str] = field(default_factory=frozenset)  # set on chat spans


def classify_trace(spans: Iterable[Span]) -> str:
    """Return AUTHORITATIVE only if call.id linkage and timestamp sort agree."""
    spans = list(spans)

    executed = {s.tool_call_id for s in spans if s.operation == "execute_tool" and s.tool_call_id}
    referenced = set()
    for s in spans:
        if s.operation == "chat":
            referenced |= set(s.referenced_call_ids)

    if executed != referenced:
        missing = executed.symmetric_difference(referenced)
        raise TraceOrderAmbiguousError(
            f"call.id linkage mismatch; unreconciled ids: {sorted(missing)}"
        )

    ordered = sorted(spans, key=lambda s: s.start_unix_nano)
    seen_referenced: set[str] = set()
    for s in ordered:
        if s.operation == "chat":
            seen_referenced |= set(s.referenced_call_ids)
        elif s.operation == "execute_tool" and s.tool_call_id:
            if s.tool_call_id not in seen_referenced:
                raise TraceOrderAmbiguousError(
                    f"execute_tool(call_id={s.tool_call_id}) sorts before the chat span "
                    f"that references it; timestamp order contradicts turn linkage"
                )
    return "AUTHORITATIVE"
