# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-span-emission-when-opentelemetry-genai-token-accounting-attributes-diverge-from-the-reasoning-trajectory-s-terminal-state.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-span-emission-when-opentelemetry-genai-token-accounting-attributes-diverge-from-the-reasoning-trajectory-s-terminal-state.warrant.json
# Markdown SHA-256:   5fe2fec3d863ad442edbf763b7614a1f4844d9cd961f102874b2104d7854d28c
# Code AST SHA-256:   bae3ae8ffbefa1eb6e21a03996906ef1ca97c8064a3c84c9937d4ee807008d34
# Verified Classes:   UsageAttributionError, ChildSpanUsage, ParentTrajectory
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UsageAttributionError(RuntimeError):
    """Raised when a parent agent span cannot lawfully emit a usage rollup."""


@dataclass
class ChildSpanUsage:
    span_id: str
    closed: bool
    input_tokens: int = 0
    output_tokens: int = 0
    cache_read_input_tokens: int = 0
    is_retry_attempt: bool = False
    exported: bool = True


@dataclass
class ParentTrajectory:
    span_id: str
    children: list[ChildSpanUsage] = field(default_factory=list)
    subtree_sampled_uniformly: bool = True


def _partitioned_input(c: ChildSpanUsage) -> int:
    # Convention: input_tokens is exclusive of cache reads for rollup purposes.
    return max(c.input_tokens - c.cache_read_input_tokens, 0)


def compute_authoritative_rollup(parent: ParentTrajectory) -> dict:
    """Return a rollup dict ONLY if every validity conjunct holds; else raise."""
    if not parent.subtree_sampled_uniformly:
        raise UsageAttributionError(
            f"span {parent.span_id}: subtree sampling non-uniform; "
            "rollup would be unverifiable"
        )

    for c in parent.children:
        if c.exported and not c.closed:
            raise UsageAttributionError(
                f"span {parent.span_id}: child {c.span_id} not closed before "
                "parent close; rollup would over-count"
            )

    # Retries: count usage exactly once, from the exported successful attempt.
    retried = [c for c in parent.children if c.is_retry_attempt]
    if len(retried) > 1 and any(c.exported and (c.input_tokens or c.output_tokens) for c in retried):
        raise UsageAttributionError(
            f"span {parent.span_id}: multiple retry attempts carry usage; "
            "double-count risk"
        )

    rollup_input = 0
    rollup_output = 0
    rollup_cache = 0
    for c in parent.children:
        if not c.exported:
            continue
        if c.is_retry_attempt and (c.input_tokens or c.output_tokens):
            # successful retry attempt: count once
            rollup_input += _partitioned_input(c)
            rollup_output += c.output_tokens
            rollup_cache += c.cache_read_input_tokens
        elif not c.is_retry_attempt:
            rollup_input += _partitioned_input(c)
            rollup_output += c.output_tokens
            rollup_cache += c.cache_read_input_tokens

    return {
        "gen_ai.usage.input_tokens": rollup_input,
        "gen_ai.usage.output_tokens": rollup_output,
        "gen_ai.usage.cache_read.input_tokens": rollup_cache,
        "gen_ai.usage.attribution": "complete",
    }


def close_parent_span(parent: ParentTrajectory) -> dict:
    """Emit rollup or degrade to partial; never emit a best-effort sum."""
    try:
        return compute_authoritative_rollup(parent)
    except UsageAttributionError as e:
        # Degraded-accounting state: no authoritative totals, explicit reason.
        return {
            "gen_ai.usage.attribution": "partial",
            "gen_ai.usage.attribution_reason": str(e),
        }
