# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attributes-tokens-to-the-wrong-span-opentelemetry-genai-semantic-conventions-and-the-orphaned-tool-call-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attributes-tokens-to-the-wrong-span-opentelemetry-genai-semantic-conventions-and-the-orphaned-tool-call-ledger.warrant.json
# Markdown SHA-256:   21d3957e3bfff65b9da2caf8e8fc653308e5167cd473244f1115ae7250b46731
# Code AST SHA-256:   ea124d5044d68a75d86a9565abbaa4710488d25ad2ef75901f216175e0eb7442
# Verified Classes:   UsageLedgerError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UsageLedgerError(RuntimeError):
    """Raised when per-span GenAI usage attributes violate the additive-ledger invariant."""


@dataclass
class Span:
    name: str
    operation: str                      # gen_ai.operation.name
    tool_call_id: Optional[str] = None  # gen_ai.tool.call.id
    input_tokens: int = 0               # gen_ai.usage.input_tokens
    output_tokens: int = 0              # gen_ai.usage.output_tokens
    cache_read_tokens: int = 0          # gen_ai.usage.cache_read.input_tokens
    authoritative: bool = False         # corpusfetch.usage.authoritative
    rolled_up: bool = False             # corpusfetch.usage.rolled_up
    status_error: bool = False
    children: list = field(default_factory=list)


def validate_usage_ledger(spans: list[Span], billed_total: int, tolerance: int = 0) -> int:
    """
    Enforce: exactly one authoritative usage span per trace, and the sum of
    authoritative usage equals the provider's billed total within tolerance.
    Also verify every failed tool span is joinable to a chat span via tool_call_id.
    """
    authoritative = [s for s in spans if s.authoritative]
    if len(authoritative) != 1:
        raise UsageLedgerError(
            f"expected exactly 1 authoritative usage span, found {len(authoritative)}: "
            f"{[s.name for s in authoritative]}"
        )

    ledger = authoritative[0]
    ledger_total = ledger.input_tokens + ledger.output_tokens
    if abs(ledger_total - billed_total) > tolerance:
        raise UsageLedgerError(
            f"authoritative span {ledger.name!r} reports {ledger_total} tokens "
            f"but provider billed {billed_total} (drift {ledger_total - billed_total})"
        )

    rolled = [s for s in spans if s.rolled_up]
    for s in rolled:
        if s.input_tokens or s.output_tokens:
            raise UsageLedgerError(
                f"rolled-up span {s.name!r} carries usage attributes "
                f"({s.input_tokens}/{s.output_tokens}); double-counting risk"
            )

    chat_ids = {s.tool_call_id for s in spans if s.operation == "chat" and s.tool_call_id}
    for s in spans:
        if s.operation == "execute_tool" and s.status_error:
            if s.tool_call_id is None or s.tool_call_id not in chat_ids:
                raise UsageLedgerError(
                    f"failed tool span {s.name!r} (call_id={s.tool_call_id!r}) "
                    f"is orphaned: billed argument tokens cannot be recovered via join"
                )

    return ledger_total


# --- Trigger trace: three-iteration agent, one orphaned failed tool -------------
trace = [
    Span("invoke_agent", "invoke_agent", authoritative=True,
         input_tokens=18_400, output_tokens=1_378),          # ledger
    Span("chat.1", "chat", tool_call_id="call_a", rolled_up=True,
         input_tokens=4_000, output_tokens=410),
    Span("execute_tool.a", "execute_tool", tool_call_id="call_a"),
    Span("chat.2", "chat", tool_call_id="call_b", rolled_up=True,
         input_tokens=6_200, output_tokens=512),
    Span("execute_tool.b", "execute_tool", tool_call_id="call_b", status_error=True),
    Span("chat.3", "chat", rolled_up=True,
         input_tokens=8_200, output_tokens=456),
]

try:
    validate_usage_ledger(trace, billed_total=6_190)
except UsageLedgerError as exc:
    print(f"LEDGER REJECTED: {exc}")
