# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-an-opentelemetry-genai-span-the-token-accounting-reconciliation-invariant-across-parent-child-tool-call-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-an-opentelemetry-genai-span-the-token-accounting-reconciliation-invariant-across-parent-child-tool-call-spans.warrant.json
# Markdown SHA-256:   3ce8bb2caa8c6a7e1db6c42066ad0df0fcffa72a487b4e8387048b589bdd3966
# Code AST SHA-256:   08f55afa85618bfd52e2b317069dd90a59a0e85d959b5e548d60b0ac8998254f
# Verified Classes:   UnreconciledUsageError, TokenAccumulator, InvocationSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnreconciledUsageError(RuntimeError):
    """Raised when a model-invocation span would emit token usage that cannot be
    reconciled to a per-invocation delta with a terminal finish reason."""


@dataclass
class TokenAccumulator:
    value: int = 0

    def add(self, n: int) -> None:
        self.value += n


@dataclass
class InvocationSpan:
    span_id: str
    base: int = 0
    finish_reasons: Optional[list] = None
    usage: Optional[dict] = field(default=None)


def open_invocation(span_id: str, acc: TokenAccumulator) -> InvocationSpan:
    # Capture the loop-scoped base at open; the delta is measured against this.
    return InvocationSpan(span_id=span_id, base=acc.value)


def close_invocation(
    span: InvocationSpan,
    acc: TokenAccumulator,
    finish_reasons: Optional[list],
    tool_call_ids: list,
) -> InvocationSpan:
    span.finish_reasons = finish_reasons
    delta_in = acc.value - span.base

    # Guardrail: the only states in which usage may be emitted.
    if finish_reasons is None:
        # Invocation never reached a terminal state (crash, timeout, context
        # saturation). Emitting acc.value here is the silent-overcount bug.
        span.usage = None
        span.unreconciled = True  # consumer routes to quarantine
        return span

    if delta_in < 0:
        # Accumulator was reset or shared across concurrent loops.
        raise UnreconciledUsageError(
            f"span {span.span_id}: negative token delta ({delta_in}); "
            f"accumulator base={span.base} current={acc.value}. "
            f"Accumulator is not invocation-scoped."
        )

    span.usage = {
        "gen_ai.usage.input_tokens": delta_in,
        "gen_ai.response.finish_reasons": finish_reasons,
        "gen_ai.tool.call.ids": tool_call_ids,
    }
    return span


def reconcile_trace(spans: list[InvocationSpan]) -> int:
    """Post-export identity check: sum of deltas must equal the final
    invocation's base+delta, i.e. no accumulator snapshot leaked in."""
    if not spans:
        return 0
    total = sum(s.usage["gen_ai.usage.input_tokens"] for s in spans if s.usage)
    last = spans[-1]
    if last.usage is None:
        raise UnreconciledUsageError(
            f"trace ends on unreconciled span {last.span_id}; "
            f"cannot verify cost identity"
        )
    expected = last.base + last.usage["gen_ai.usage.input_tokens"]
    if total != expected:
        raise UnreconciledUsageError(
            f"trace token identity violated: sum(deltas)={total} "
            f"!= final base+delta={expected}"
        )
    return total
