# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-usage-attributes-when-a-streaming-model-invocation-is-retried-mid-flight-and-the-span-is-re.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-usage-attributes-when-a-streaming-model-invocation-is-retried-mid-flight-and-the-span-is-re.warrant.json
# Markdown SHA-256:   ad33be73d74e9897d5c1203256d0a3ee2fe7e513e2d0f15ac7ff54ca9447d15c
# Code AST SHA-256:   1b600b3383dc4088f4049ed2f9b54614301b421e6bd6a749ad027dbd79c14e1e
# Verified Classes:   TokenAccountingInvariantError, AttemptSpan, ReconciledUsage
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class TokenAccountingInvariantError(RuntimeError):
    """Raised when a logical model invocation's telemetry violates the
    committed-vs-billed token reconciliation invariant."""


@dataclass
class AttemptSpan:
    span_id: str
    invocation_id: str | None
    role: Literal["committed", "aborted", "unknown"]
    input_tokens: int
    output_tokens: int


@dataclass
class ReconciledUsage:
    semantic_input_tokens: int
    semantic_output_tokens: int
    billed_input_tokens: int
    billed_output_tokens: int


def reconcile_invocation(spans: list[AttemptSpan]) -> ReconciledUsage:
    if not spans:
        raise TokenAccountingInvariantError("no attempt spans for invocation")

    # Invariant 1: every span must carry a correlation key.
    missing = [s.span_id for s in spans if not s.invocation_id]
    if missing:
        raise TokenAccountingInvariantError(
            f"attempt spans missing gen_ai.invocation.id: {missing}; "
            "cannot dedupe retried usage"
        )

    # Invariant 2: all spans must belong to the same logical invocation.
    ids = {s.invocation_id for s in spans}
    if len(ids) != 1:
        raise TokenAccountingInvariantError(
            f"spans span multiple invocations {ids}; refusing to reconcile"
        )

    # Invariant 3: exactly one committed attempt, or none (total failure).
    committed = [s for s in spans if s.role == "committed"]
    if len(committed) > 1:
        raise TokenAccountingInvariantError(
            f"multiple committed attempts {[s.span_id for s in committed]}; "
            "semantic output is ambiguous"
        )

    # Invariant 4: no span may have unknown role — role is required to
    # distinguish billed-but-discarded from billed-and-committed tokens.
    unknown = [s.span_id for s in spans if s.role == "unknown"]
    if unknown:
        raise TokenAccountingInvariantError(
            f"attempt spans with unresolved role: {unknown}; "
            "aborted output tokens would silently roll into semantic totals"
        )

    # Billed cost sums across ALL attempts (money was spent).
    billed_in = sum(s.input_tokens for s in spans)
    billed_out = sum(s.output_tokens for s in spans)

    # Semantic totals come from the committed attempt only.
    if committed:
        semantic_in = committed[0].input_tokens
        semantic_out = committed[0].output_tokens
    else:
        semantic_in = 0
        semantic_out = 0

    return ReconciledUsage(
        semantic_input_tokens=semantic_in,
        semantic_output_tokens=semantic_out,
        billed_input_tokens=billed_in,
        billed_output_tokens=billed_out,
    )


# Reproduces the observed failure: two sibling spans, no correlation key,
# roles unresolved. The reconciler must refuse rather than double-count.
observed = [
    AttemptSpan("a1", None, "unknown", 1840, 612),
    AttemptSpan("a2", None, "unknown", 1840, 2011),
]
try:
    reconcile_invocation(observed)
except TokenAccountingInvariantError as e:
    print(f"BLOCKED: {e}")

# Corrected emission: shared invocation id, explicit roles.
corrected = [
    AttemptSpan("a1", "inv-7f3a", "aborted", 1840, 612),
    AttemptSpan("a2", "inv-7f3a", "committed", 1840, 2011),
]
usage = reconcile_invocation(corrected)
assert usage.semantic_output_tokens == 2011   # what the agent actually used
assert usage.billed_output_tokens == 2623     # what the provider billed
assert usage.semantic_input_tokens == 1840    # one logical prompt
assert usage.billed_input_tokens == 3680      # prompt billed twice
print(usage)
