# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-opentelemetry-genai-agent-spans-when-tool-call-attributes-and-token-accounting-disagree-across-span-boundari.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-opentelemetry-genai-agent-spans-when-tool-call-attributes-and-token-accounting-disagree-across-span-boundari.warrant.json
# Markdown SHA-256:   470008fd127b81a63bd4dca1c7bd3ccbda2ab8f3b4f93af287112427692bd8c1
# Code AST SHA-256:   c478507eaba2cc541685d7abaa72c819c6921500d91de86194f69c93d55f5dcb
# Verified Classes:   GenAIAccountingAmbiguity, Usage, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class GenAIAccountingAmbiguity(RuntimeError):
    """Raised when an agent span's token accounting model cannot be determined."""


@dataclass(frozen=True)
class Usage:
    input_tokens: int
    output_tokens: int


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_span_id: str | None
    operation_name: str
    tool_call_id: str | None
    usage: Usage | None


CUMULATIVE_RATIO_LOW = 0.95
CUMULATIVE_RATIO_HIGH = 1.05


def classify_agent_span(parent: Span, descendants: list[Span]) -> str:
    """Return 'additive', 'cumulative', or 'ambiguous' for a parent agent span.

    Raises GenAIAccountingAmbiguity when the parent reports usage but no
    descendant does, or when the ratio lands in the ambiguous band with
    insufficient evidence to disambiguate.
    """
    if parent.operation_name not in {"invoke_agent", "create_agent"}:
        raise GenAIAccountingAmbiguity(
            f"span {parent.span_id} is not an agent span: {parent.operation_name}"
        )

    if parent.usage is None:
        return "additive"

    child_inputs = [
        d.usage.input_tokens for d in descendants if d.usage is not None
    ]
    if not child_inputs:
        raise GenAIAccountingAmbiguity(
            f"agent span {parent.span_id} reports usage but no descendant does; "
            "cannot distinguish cumulative from additive without child evidence"
        )

    if len(child_inputs) < 2:
        # Single-child trees are mathematically indistinguishable.
        return "ambiguous"

    child_sum = sum(child_inputs)
    if child_sum == 0:
        raise GenAIAccountingAmbiguity(
            f"agent span {parent.span_id} has descendants with zero input tokens"
        )

    ratio = parent.usage.input_tokens / child_sum
    if CUMULATIVE_RATIO_LOW <= ratio <= CUMULATIVE_RATIO_HIGH:
        return "cumulative"
    if ratio < CUMULATIVE_RATIO_LOW:
        return "additive"
    # ratio > HIGH: parent exceeds all children combined; genuine anomaly.
    raise GenAIAccountingAmbiguity(
        f"agent span {parent.span_id} input_tokens={parent.usage.input_tokens} "
        f"exceeds descendant sum={child_sum} (ratio={ratio:.3f}); "
        "route to anomaly alert, do not merge into billing"
    )


def should_quarantine(parent: Span, descendants: list[Span]) -> bool:
    try:
        model = classify_agent_span(parent, descendants)
    except GenAIAccountingAmbiguity:
        return True
    return model in {"cumulative", "ambiguous"}
