# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-genai-span-tree-when-token-usage-attributes-disagree-across-nested-agent-and-tool-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-genai-span-tree-when-token-usage-attributes-disagree-across-nested-agent-and-tool-spans.warrant.json
# Markdown SHA-256:   bfd6b221c47e27717eb3a52921bd1d443ed52f889740da66eefef6d616c6e8d0
# Code AST SHA-256:   4b178e68800ef081414fa9f954ffcf30b2c6e90373c73b99ca2e2c057d79be25
# Verified Classes:   GenAIAttributionConflict, SpanUsage
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class GenAIAttributionConflict(RuntimeError):
    """Raised when a GenAI span tree's summed descendant usage exceeds the
    root's provider-authoritative usage, indicating double-attributed tokens."""
    pass


@dataclass
class SpanUsage:
    span_id: str
    operation: str  # "invoke_agent" | "chat" | "execute_tool"
    input_tokens: int
    output_tokens: int


TOLERANCE = 0.05  # 5% absorbs tokenizer/cache rounding


def close_span_tree(root: SpanUsage, descendants: list[SpanUsage]) -> dict:
    """Enforce the tree-sum invariant at trace close.

    Returns a dict with authoritative usage and a non-additive breakdown.
    Raises GenAIAttributionConflict when descendants double-count root context.
    """
    desc_input = sum(s.input_tokens for s in descendants)
    desc_output = sum(s.output_tokens for s in descendants)

    if root.input_tokens <= 0:
        raise GenAIAttributionConflict(
            f"root span {root.span_id} reports non-positive input_tokens="
            f"{root.input_tokens}; cannot establish authoritative baseline"
        )

    overage = (desc_input - root.input_tokens) / root.input_tokens
    if overage > TOLERANCE:
        # Double-attribution detected: children replayed shared context.
        # Do NOT emit tree-sum as cost. Fall back to root-authoritative.
        raise GenAIAttributionConflict(
            f"tree-sum input_tokens={desc_input} exceeds root-authoritative "
            f"{root.input_tokens} by {overage:.1%} (> {TOLERANCE:.0%}); "
            f"descendant usage is a breakdown, not an addend. "
            f"root={root.span_id}, descendants={[s.span_id for s in descendants]}"
        )

    return {
        "authoritative_input_tokens": root.input_tokens,
        "authoritative_output_tokens": root.output_tokens,
        "breakdown": {
            "additive": True,
            "descendant_input_tokens": desc_input,
            "descendant_output_tokens": desc_output,
        },
    }
