# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-span-attribute-divergence-between-genai-semantic-conventions-and-its-own-tool-call-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-span-attribute-divergence-between-genai-semantic-conventions-and-its-own-tool-call-ledger.warrant.json
# Markdown SHA-256:   66380e76936be4c5b200a212b36fca4f5824d617ea04315d4f215d22746e082b
# Code AST SHA-256:   f5e2988148f0ca138f8ed331b0defcbdca3bea127cfe296393c999619778d5de
# Verified Classes:   SpanLedgerDivergence, ReconciliationMode, SpanRecord, LedgerRow
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Iterable


class SpanLedgerDivergence(RuntimeError):
    """Raised when GenAI span token accounting and the tool-call ledger disagree
    in a direction that cannot be explained by in-flight retries."""


class ReconciliationMode(Enum):
    TELEMETRY_AUTHORITATIVE = "telemetry_authoritative"
    LEDGER_AUTHORITATIVE = "ledger_authoritative"


@dataclass(frozen=True)
class SpanRecord:
    call_id: str
    tool_name: str
    output_tokens: int
    attempt: int | None  # None means the runtime did not emit an attempt attribute


@dataclass(frozen=True)
class LedgerRow:
    call_id: str
    call_seq: int
    committed_tokens: int
    pre_debited_tokens: int  # tokens charged before the call returned


def reconcile_turn(
    spans: Iterable[SpanRecord],
    ledger: Iterable[LedgerRow],
    mode: ReconciliationMode,
) -> None:
    span_by_call: dict[str, list[SpanRecord]] = {}
    for s in spans:
        span_by_call.setdefault(s.call_id, []).append(s)

    ledger_by_call = {row.call_id: row for row in ledger}

    for call_id, rows in span_by_call.items():
        if len(rows) > 1 and any(r.attempt is None for r in rows):
            # Multiple spans for one call id with no attempt attribute:
            # indistinguishable from duplicate emission. Cannot reconcile.
            raise SpanLedgerDivergence(
                f"call_id={call_id!r} has {len(rows)} spans but no attempt "
                f"attribute; retry vs duplicate emission is undecidable"
            )

    if mode is ReconciliationMode.TELEMETRY_AUTHORITATIVE:
        for call_id, row in ledger_by_call.items():
            matching = span_by_call.get(call_id, [])
            if len(matching) != 1:
                raise SpanLedgerDivergence(
                    f"ledger call_id={call_id!r} seq={row.call_seq} expected "
                    f"exactly one span, found {len(matching)}"
                )
            if matching[0].output_tokens != row.committed_tokens:
                raise SpanLedgerDivergence(
                    f"call_id={call_id!r} span tokens={matching[0].output_tokens} "
                    f"!= ledger committed={row.committed_tokens}"
                )
    else:  # LEDGER_AUTHORITATIVE
        span_total = sum(s.output_tokens for s in spans)
        ledger_total = sum(r.committed_tokens for r in ledger)
        pre_debit_total = sum(r.pre_debited_tokens for r in ledger)
        # Spans may over-count (retries regenerate tokens) but must never
        # under-count below the ledger's committed total. A shortfall means
        # the exporter dropped spans and the ledger is the only truth.
        if span_total < ledger_total:
            raise SpanLedgerDivergence(
                f"span token sum={span_total} < ledger committed={ledger_total}; "
                f"dropped spans suspected (pre-debit total={pre_debit_total})"
            )
        # Pre-debits from failed attempts must be reversed on retry; if they
        # were not, the ledger overstates committed spend relative to spans.
        unreversed = pre_debit_total - sum(
            r.pre_debited_tokens for r in ledger if r.committed_tokens == 0
        )
        if unreversed > 0 and span_total > ledger_total + unreversed:
            raise SpanLedgerDivergence(
                f"span sum={span_total} exceeds ledger+pre-debit by "
                f"{span_total - ledger_total - unreversed}; "
                f"pre-debit reversal missing on retried calls"
            )
