# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-attributes-when-a-tool-call-span-is-exported-before-its-parent-agent-span-closes-causing-tok.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-attributes-when-a-tool-call-span-is-exported-before-its-parent-agent-span-closes-causing-tok.warrant.json
# Markdown SHA-256:   173e6d5c33396dd70a2b43f8f240eaeda9279ed59bffc79190e80b513d96326e
# Code AST SHA-256:   eae3e6f9007320b4ae779516135c482284cea0c105bada257c35903cc8a0631f
# Verified Classes:   GenAIUsageContractError, Span
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Policy = Literal["leaf_attribution", "rollup"]

class GenAIUsageContractError(RuntimeError):
    """Raised when a span violates the leaf/rollup usage-attribution invariant."""

@dataclass
class Span:
    span_id: str
    trace_id: str
    operation_name: str
    policy: Policy
    usage_input: int | None = None
    usage_output: int | None = None
    counted_children: set[str] = field(default_factory=set)
    ended: bool = False

LEAF_OPS = {"chat", "text_completion", "embeddings"}
ROLLUP_OPS = {"invoke_agent", "execute_tool", "create_agent"}

def end_span(span: Span, child_spans: list[Span]) -> None:
    if span.ended:
        raise GenAIUsageContractError(
            f"span {span.span_id} ended twice; re-export would double-count usage"
        )

    has_usage = span.usage_input is not None or span.usage_output is not None

    if span.policy == "leaf_attribution":
        if span.operation_name in ROLLUP_OPS and has_usage:
            raise GenAIUsageContractError(
                f"rollup op {span.operation_name} ({span.span_id}) carries "
                f"gen_ai.usage.* under leaf_attribution policy; summing the tree "
                f"will double-count child tokens"
            )
        if span.operation_name in LEAF_OPS and not has_usage:
            raise GenAIUsageContractError(
                f"leaf op {span.operation_name} ({span.span_id}) missing "
                f"gen_ai.usage.*; its tokens will vanish from the trace total"
            )

    if span.policy == "rollup":
        if span.operation_name in LEAF_OPS and has_usage:
            raise GenAIUsageContractError(
                f"leaf op {span.operation_name} ({span.span_id}) carries usage "
                f"under rollup policy; parent will re-sum and double-count"
            )
        if span.operation_name in ROLLUP_OPS:
            unended = [c.span_id for c in child_spans if not c.ended]
            if unended:
                raise GenAIUsageContractError(
                    f"rollup span {span.span_id} closing before children "
                    f"{unended} ended; aggregate would undercount (vanish race)"
                )
            expected = {c.span_id for c in child_spans}
            if span.counted_children != expected:
                raise GenAIUsageContractError(
                    f"rollup span {span.span_id} counted {span.counted_children} "
                    f"but children are {expected}; reconciliation set mismatch"
                )

    span.ended = True

def reconcile_trace_total(spans: list[Span]) -> int:
    """Sum usage only over spans permitted to carry it under a single policy."""
    policies = {s.policy for s in spans}
    if len(policies) > 1:
        raise GenAIUsageContractError(
            f"mixed attribution policies in one trace: {policies}; "
            f"tree sum is undefined"
        )
    seen: set[str] = set()
    total = 0
    for s in spans:
        if s.span_id in seen:
            raise GenAIUsageContractError(
                f"duplicate span_id {s.span_id} in trace; re-export detected"
            )
        seen.add(s.span_id)
        total += (s.usage_input or 0) + (s.usage_output or 0)
    return total
