# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-agent-spans-as-authoritative-for-token-attribution.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-agent-spans-as-authoritative-for-token-attribution.warrant.json
# Markdown SHA-256:   c3828b97c5102bec6d4f8dcefd722eb017832eb53f9a82c3dc5ecec7bbddfd59
# Code AST SHA-256:   eaceecdede05cc4aacfcf65c5098a77794f803f282e2ec23efc2b135c42d710b
# Verified Classes:   AttributionInvariantError, Span
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class AttributionInvariantError(RuntimeError):
    """Raised when a span tree cannot be safely attributed for token cost."""


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    operation: str  # gen_ai.operation.name
    input_tokens: int | None
    output_tokens: int | None
    sampled: bool = True
    children: list["Span"] = field(default_factory=list)


INFERENCE_OPS = {"chat", "text_completion", "invoke_agent"}


def attribute_subtree_tokens(root: Span) -> int:
    """Sum token usage across inference-bearing spans in a subtree.

    Never reads a non-inference span's usage as a total. Raises if the
    subtree is incomplete, because a partial sum silently under-reports.
    """
    if not root.sampled:
        raise AttributionInvariantError(
            f"span {root.span_id} is unsampled; subtree total is a lower bound, "
            "not a total, and must not be reported as one"
        )

    total = 0
    stack = [root]
    while stack:
        span = stack.pop()
        if not span.sampled:
            raise AttributionInvariantError(
                f"descendant span {span.span_id} of {root.span_id} is unsampled; "
                "subtree attribution is incomplete"
            )
        if span.operation in INFERENCE_OPS:
            if span.input_tokens is None or span.output_tokens is None:
                raise AttributionInvariantError(
                    f"inference span {span.span_id} has partial usage "
                    f"(input={span.input_tokens}, output={span.output_tokens}); "
                    "refusing to sum an incomplete record"
                )
            if span.input_tokens < 0 or span.output_tokens < 0:
                raise AttributionInvariantError(
                    f"inference span {span.span_id} reports negative usage"
                )
            total += span.input_tokens + span.output_tokens
        stack.extend(span.children)
    return total


def attribute_root_span_as_total(root: Span) -> int:
    """The boundary failure, made explicit so it cannot be done by accident."""
    if root.children:
        raise AttributionInvariantError(
            f"agent span {root.span_id} has {len(root.children)} descendants; "
            "its gen_ai.usage.* describes only its own model call, not the subtree. "
            "Use attribute_subtree_tokens instead."
        )
    if root.input_tokens is None or root.output_tokens is None:
        raise AttributionInvariantError(
            f"agent span {root.span_id} lacks complete usage attributes"
        )
    return root.input_tokens + root.output_tokens
