# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-span-attribute-divergence-when-opentelemetry-genai-token-accounting-is-reconciled-against-agent-tool-call-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-span-attribute-divergence-when-opentelemetry-genai-token-accounting-is-reconciled-against-agent-tool-call-spans.warrant.json
# Markdown SHA-256:   46083f73df3e8ef012c57dd3f436fa2c501bd58b3305661f704dc2e27e216e6e
# Code AST SHA-256:   7aa9247060e2d90878e7303c05dd5caf049c7a84f4ca88768305b9788c7d350c
# Verified Classes:   GenAIAccountingDivergence, SpanUsage
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class GenAIAccountingDivergence(RuntimeError):
    """Raised when agent-span token accounting violates the reconciliation invariant."""
    pass


@dataclass
class SpanUsage:
    name: str
    operation: str            # "chat" | "execute_tool" | "agent"
    input_tokens: int = 0
    output_tokens: int = 0
    has_model: bool = False
    usage_scope: str = "local"  # "local" | "aggregate"


def reconcile_agent_span(parent: SpanUsage, children: list[SpanUsage],
                        preamble_tolerance: int = 0) -> dict:
    chat_leaves = [c for c in children if c.operation == "chat"]
    tool_leaves = [c for c in children if c.operation == "execute_tool"]

    # Invariant 1: tool spans must not be required to carry usage.
    for t in tool_leaves:
        if t.input_tokens or t.output_tokens:
            raise GenAIAccountingDivergence(
                f"tool span {t.name!r} carries token usage; convention forbids it"
            )

    leaf_in = sum(c.input_tokens for c in chat_leaves)
    leaf_out = sum(c.output_tokens for c in chat_leaves)

    # Invariant 2: leaves must not exceed parent (double-counted retries).
    if leaf_in > parent.input_tokens or leaf_out > parent.output_tokens:
        raise GenAIAccountingDivergence(
            f"leaf usage {leaf_in}/{leaf_out} exceeds parent "
            f"{parent.input_tokens}/{parent.output_tokens}; likely double-counted retries"
        )

    # Invariant 3: aggregate parent without model cannot be priced.
    if parent.usage_scope == "aggregate" and not parent.has_model:
        residual = parent.input_tokens - leaf_in
        if residual > preamble_tolerance:
            raise GenAIAccountingDivergence(
                f"aggregate parent lacks gen_ai.request.model; "
                f"{residual} input tokens unattributable beyond tolerance {preamble_tolerance}"
            )

    return {
        "billable_input": leaf_in,
        "billable_output": leaf_out,
        "unattributed_input": parent.input_tokens - leaf_in,
        "scope": parent.usage_scope,
    }
