# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-token-accounting-divergence-between-opentelemetry-genai-span-attributes-and-the-agent-s-own-usage-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-token-accounting-divergence-between-opentelemetry-genai-span-attributes-and-the-agent-s-own-usage-ledger.warrant.json
# Markdown SHA-256:   b073cdd5be4296782487689b247a935690674b8b6c49533885aef9e2b50d4bad
# Code AST SHA-256:   fbb91a010c56615197f90c784d5dafc4b888a97cd59c46a284105b0d5337ef20
# Verified Classes:   TokenAccountingDivergence, SpanUsage, LedgerEntry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import dataclasses
from typing import Optional


class TokenAccountingDivergence(RuntimeError):
    """Raised when OTel GenAI span usage cannot be reconciled with the agent ledger."""
    pass


@dataclasses.dataclass
class SpanUsage:
    operation: str
    input_tokens: Optional[int]
    output_tokens: Optional[int]
    status_code: str  # "OK" or "ERROR"
    request_model: Optional[str]
    response_model: Optional[str]
    child_input_sum: int = 0
    parent_prompt_estimate: int = 0


@dataclasses.dataclass
class LedgerEntry:
    operation: str
    debited_tokens: int
    transaction_count: int


def reconcile_span_to_ledger(
    span: SpanUsage,
    ledger: LedgerEntry,
    span_count_for_op: int,
) -> int:
    """
    Validate that a closed GenAI span's usage attributes are structurally
    reconcilable with the ledger. Returns the tokens to credit back to the
    ledger on success; raises TokenAccountingDivergence on any structural
    violation, in which case the caller must retain the conservative
    pre-estimate rather than promoting span usage to ledger truth.
    """
    # Signal 3: output tokens on an ERROR span are impossible.
    if span.status_code == "ERROR" and (span.output_tokens or 0) > 0:
        raise TokenAccountingDivergence(
            f"output_tokens={span.output_tokens} on ERROR span for op={span.operation}; "
            "attribute likely copied from prior attempt or fallback provider"
        )

    # Signal 1: retry collapse — more spans than ledger transactions.
    if span_count_for_op > ledger.transaction_count:
        raise TokenAccountingDivergence(
            f"span_count={span_count_for_op} > ledger.transactions={ledger.transaction_count} "
            f"for op={span.operation}; retries emitted spans that ledger collapsed"
        )

    # Signal 2: parent attribute non-additive across children.
    if span.input_tokens is not None:
        floor = span.child_input_sum + span.parent_prompt_estimate
        if span.input_tokens < floor:
            raise TokenAccountingDivergence(
                f"parent input_tokens={span.input_tokens} < child_sum+prompt={floor} "
                f"for op={span.operation}; attribute overwritten instead of accumulated"
            )

    # Signal 4: response model diverged from request model without rate adjustment.
    if (
        span.request_model is not None
        and span.response_model is not None
        and span.request_model != span.response_model
        and ledger.debited_tokens == 0
    ):
        raise TokenAccountingDivergence(
            f"fallback model {span.response_model} served request for {span.request_model} "
            f"but ledger has no rate-adjusted debit for op={span.operation}"
        )

    # Signal 5: streaming span closed without usage.
    if span.input_tokens is None or span.output_tokens is None:
        raise TokenAccountingDivergence(
            f"span for op={span.operation} closed without complete gen_ai.usage; "
            "streaming abort or premature span close — retain pre-estimate"
        )

    return span.input_tokens + span.output_tokens
