# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-from-silently-corrupting-agent-span-trees-under-opentelemetry-genai-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-from-silently-corrupting-agent-span-trees-under-opentelemetry-genai-semantic-conventions.warrant.json
# Markdown SHA-256:   64a6f19442929d397706c281c041adbe8408169313c7ec0c5f78d470d8ab7591
# Code AST SHA-256:   0ec2c3c63bda4d0dd5bd0dea5a93d76ebae185659fb3c928469757c6bfc20990
# Verified Classes:   TokenAccountingError, AccountingMode, GenAISpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class TokenAccountingError(RuntimeError):
    """Raised when a span-tree token rollup cannot be resolved to a
    well-defined accounting mode (transmitted vs. contributed)."""


class AccountingMode(Enum):
    TRANSMITTED = "transmitted"   # every request that hit the wire, incl. discarded
    CONTRIBUTED = "contributed"   # only leaves that produced the committed answer


@dataclass
class GenAISpan:
    span_id: str
    operation: str                     # e.g. "chat", "tool"
    input_tokens: int = 0
    output_tokens: int = 0
    discarded: bool = False            # response not part of committed output (retry, lost spec)
    injected_from: tuple[str, ...] = ()  # sibling span_ids whose content entered this prompt
    children: list["GenAISpan"] = field(default_factory=list)


def rollup_tokens(root: GenAISpan, mode: AccountingMode) -> int:
    """Sum token usage over a span subtree under a declared accounting mode.

    Invariant: CONTRIBUTED excludes discarded leaves and requires that every
    injected_from edge resolve to a span present in the subtree; otherwise the
    attribution is undefined and we must refuse rather than emit a wrong number.
    """
    present = {s.span_id for s in _walk(root)}

    def visit(span: GenAISpan) -> int:
        if span.discarded and mode is AccountingMode.CONTRIBUTED:
            return 0
        if mode is AccountingMode.CONTRIBUTED:
            for src in span.injected_from:
                if src not in present:
                    raise TokenAccountingError(
                        f"span {span.span_id} ingests content from {src!r}, "
                        f"which is absent from the subtree; contribution "
                        f"attribution is undefined (likely partial-subtree "
                        f"sampling). Refusing to emit a rollup."
                    )
        total = span.input_tokens + span.output_tokens
        return total + sum(visit(c) for c in span.children)

    return visit(root)


def _walk(span: GenAISpan) -> Iterable[GenAISpan]:
    yield span
    for c in span.children:
        yield from _walk(c)


# Reproduces the observed turn: b4 is a discarded 429 retry, b3 ingests
# retrieved content sourced from b2 (the tool.search span).
turn = GenAISpan("a1", "agent.turn", children=[
    GenAISpan("b1", "chat", input_tokens=1800, output_tokens=120),
    GenAISpan("b2", "tool"),
    GenAISpan("b3", "chat", input_tokens=4100, output_tokens=340,
             injected_from=("b2",), children=[
                 GenAISpan("b4", "chat", input_tokens=4100, output_tokens=0,
                           discarded=True),
             ]),
    GenAISpan("b5", "chat", input_tokens=5900, output_tokens=60),
])

transmitted = rollup_tokens(turn, AccountingMode.TRANSMITTED)   # 16_420
contributed = rollup_tokens(turn, AccountingMode.CONTRIBUTED)   # 12_320

if contributed > transmitted:
    raise TokenAccountingError(
        "contributed tokens exceed transmitted tokens; accounting modes "
        "have been inverted or a discarded span leaked into the rollup."
    )
