# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-when-opentelemetry-genai-spans-are-re-parented-across-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-when-opentelemetry-genai-spans-are-re-parented-across-agent-handoffs.warrant.json
# Markdown SHA-256:   d3c105d0a497be916579903562ca1e0cd3f25d337e50c6793d0994dff2750c9b
# Code AST SHA-256:   5314c04e41084e77d61e32e3bfe80d5fdd5dd0971a49561c4355ed19053c9619
# Verified Classes:   TokenAccountingDrift, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable

class TokenAccountingDrift(RuntimeError):
    """Raised when trace-level token summation would double-count forwarded context."""
    pass

@dataclass
class GenAISpan:
    span_id: str
    parent_id: str | None
    input_tokens: int
    output_tokens: int
    forwarded_tokens: int = 0          # tokens inherited verbatim from parent prompt
    retry_of: str | None = None

def aggregate_trace_usage(spans: Iterable[GenAISpan]) -> tuple[int, int]:
    """Return (billed_input, billed_output) for a trace, or raise on drift."""
    by_id = {s.span_id: s for s in spans}
    billed_in = 0
    billed_out = 0

    for s in spans:
        # Retry spans: count once per retry group via max, not sum.
        if s.retry_of is not None:
            continue

        if s.forwarded_tokens > s.input_tokens:
            raise TokenAccountingDrift(
                f"span {s.span_id}: forwarded_tokens={s.forwarded_tokens} "
                f"exceeds input_tokens={s.input_tokens}"
            )

        # Walk ancestors: forwarded tokens must not exceed any ancestor's billed share.
        ancestor = by_id.get(s.parent_id) if s.parent_id else None
        while ancestor is not None:
            if s.forwarded_tokens > ancestor.input_tokens:
                raise TokenAccountingDrift(
                    f"span {s.span_id} forwards {s.forwarded_tokens} tokens but "
                    f"ancestor {ancestor.span_id} only billed {ancestor.input_tokens}"
                )
            ancestor = by_id.get(ancestor.parent_id) if ancestor.parent_id else None

        billed_in += s.input_tokens - s.forwarded_tokens
        billed_out += s.output_tokens

    # Fold retry groups: take max input/output per retry_of target.
    retry_groups: dict[str, list[GenAISpan]] = {}
    for s in spans:
        if s.retry_of is not None:
            retry_groups.setdefault(s.retry_of, []).append(s)
    for target, group in retry_groups.items():
        if target not in by_id:
            raise TokenAccountingDrift(
                f"retry group references missing span {target}"
            )
        billed_in += max(g.input_tokens - g.forwarded_tokens for g in group)
        billed_out += max(g.output_tokens for g in group)

    return billed_in, billed_out

def enforce_summable_trace(spans: list[GenAISpan]) -> None:
    """Guardrail: reject traces whose lineage cannot be reduced to a cost ledger."""
    for s in spans:
        if s.parent_id is not None and s.forwarded_tokens == 0:
            parent = next((p for p in spans if p.span_id == s.parent_id), None)
            if parent is not None and s.input_tokens > parent.output_tokens:
                # Child input exceeds what parent could have emitted: context was
                # forwarded from further up but not declared. Not summable.
                raise TokenAccountingDrift(
                    f"span {s.span_id} input_tokens={s.input_tokens} exceeds "
                    f"parent {parent.span_id} output_tokens={parent.output_tokens} "
                    f"without forwarded_tokens declaration"
                )
