# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-opentelemetry-genai-span-tree-when-token-cost-attributes-disagree-with-the-tool-call-event-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-opentelemetry-genai-span-tree-when-token-cost-attributes-disagree-with-the-tool-call-event-ledger.warrant.json
# Markdown SHA-256:   653258cec4624dc51f87bf881c91368f6e339643178fd45a2947d0c4264db261
# Code AST SHA-256:   3693c83cb02e5ac06cce7291ff37abcf77f3383e260ba4b51ad0074d1ed28b11
# Verified Classes:   GenAiSpanReconciliationError, ToolCallRecord, AgentSpanSummary
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class GenAiSpanReconciliationError(RuntimeError):
    """Raised when a GenAI span tree is spec-valid but reconciliation-invalid."""


@dataclass(frozen=True)
class ToolCallRecord:
    call_id: str
    tool_name: str
    args_hash: str
    is_retry: bool
    represented_as: str  # "span" | "event"


@dataclass(frozen=True)
class AgentSpanSummary:
    input_tokens: int
    output_tokens: int
    finish_reasons: Sequence[str]
    budget_ceiling: int
    tool_calls: Sequence[ToolCallRecord]


def assert_reconcilable(span: AgentSpanSummary) -> None:
    logical = {(c.tool_name, c.args_hash) for c in span.tool_calls}
    distinct_ids = {c.call_id for c in span.tool_calls}
    retries = sum(1 for c in span.tool_calls if c.is_retry)

    if len(distinct_ids) - len(logical) > retries:
        raise GenAiSpanReconciliationError(
            f"call-id surface non-injective: {len(distinct_ids)} ids for "
            f"{len(logical)} logical calls with only {retries} retries; "
            "id instability or event/span duplication is unresolvable"
        )

    if not span.finish_reasons and span.output_tokens >= span.budget_ceiling:
        raise GenAiSpanReconciliationError(
            f"truncation signature: output_tokens={span.output_tokens} equals "
            f"budget_ceiling={span.budget_ceiling} with no finish_reasons; "
            "trace is spec-valid but cost-under-counting"
        )

    authoritative = [c for c in span.tool_calls if c.represented_as == "span"]
    projected = [c for c in span.tool_calls if c.represented_as == "event"]
    span_ids = {c.call_id for c in authoritative}
    for ev in projected:
        if ev.call_id not in span_ids:
            raise GenAiSpanReconciliationError(
                f"event-only call {ev.call_id} on {ev.tool_name} has no "
                "authoritative span record; dedup key cannot bind it"
            )
