# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-token-cost-attribution-drift-inside-opentelemetry-genai-tool-call-span-trees.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-token-cost-attribution-drift-inside-opentelemetry-genai-tool-call-span-trees.warrant.json
# Markdown SHA-256:   a06cf42e5b8e223ba07ae1c26c1cccfd415f2d82ac06476c29bc5553efd5c234
# Code AST SHA-256:   95f4a674ff267ccf53a5e6345afbea7276c3f971bb854513592306af76c58aee
# Verified Classes:   AttributionInvariantError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

BILLABLE_OPS = {"chat", "text_completion", "embeddings", "generate_content"}


class AttributionInvariantError(RuntimeError):
    """Raised when a span tree cannot yield a single authoritative token owner."""
    pass


@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    operation_name: Optional[str]
    input_tokens: int = 0
    output_tokens: int = 0
    children: list = field(default_factory=list)


def is_billable(span: Span) -> bool:
    return span.operation_name in BILLABLE_OPS


def has_billable_descendant(span: Span) -> bool:
    stack = list(span.children)
    while stack:
        node = stack.pop()
        if is_billable(node) and (node.input_tokens or node.output_tokens):
            return True
        stack.extend(node.children)
    return False


def attribute_trace(root: Span) -> tuple[int, list[str]]:
    """Return (authoritative_total_tokens, ambiguous_span_ids).

    Leaf-only rule: a span carrying usage is authoritative ONLY if it has no
    billable descendant that also carries usage. Otherwise its usage is a
    duplicate copy and is excluded from the rollup.
    """
    total = 0
    ambiguous: list[str] = []
    stack = [root]
    while stack:
        span = stack.pop()
        carries = bool(span.input_tokens or span.output_tokens)
        if carries:
            if has_billable_descendant(span):
                # ancestor duplicated a descendant's usage -> exclude
                pass
            elif not is_billable(span) and not any(
                is_billable(c) for c in span.children
            ):
                # usage on a non-billable span with no billable child:
                # the embedding-tool under-count case, cannot resolve
                ambiguous.append(span.span_id)
                total += span.input_tokens + span.output_tokens
            else:
                total += span.input_tokens + span.output_tokens
        stack.extend(span.children)

    if ambiguous:
        # Surface, do not silently accept: cost rollup is unreliable.
        raise AttributionInvariantError(
            f"ambiguous attribution on spans {ambiguous}: "
            f"usage present but no billable operation tagged; "
            f"rollup total {total} may under-count provider invoice"
        )
    return total, ambiguous


def reconcile(root: Span, provider_invoice_tokens: int, tol: float = 0.02) -> None:
    total, _ = attribute_trace(root)
    if provider_invoice_tokens == 0:
        return
    drift = abs(total - provider_invoice_tokens) / provider_invoice_tokens
    if drift > tol:
        raise AttributionInvariantError(
            f"attribution drift {drift:.3f} exceeds tolerance {tol}: "
            f"summed={total} invoice={provider_invoice_tokens}"
        )
