# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-parent-span-s-gen-ai-usage-token-counts-after-a-tool-call-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-parent-span-s-gen-ai-usage-token-counts-after-a-tool-call-fan-out.warrant.json
# Markdown SHA-256:   1440550363535c5fee3798756955da5e814d1891a71a2929c8abb01335fb2fbb
# Code AST SHA-256:   1bb6869b859bbe968581e41f646cda609f52363f0def91a0d64127a8af5a1528
# Verified Classes:   UnaccountableTraceError, GenAISpan
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class UnaccountableTraceError(RuntimeError):
    """Raised when a trace's token total cannot be defensibly derived from span closure."""


@dataclass(frozen=True)
class GenAISpan:
    span_id: str
    parent_id: str | None
    operation: str                # gen_ai.operation.name
    end_time_ns: int
    input_tokens: int | None      # gen_ai.usage.input_tokens, None if absent
    output_tokens: int | None
    response_model: str | None    # gen_ai.response.model
    aggregation: str | None = None  # custom subtree_sum marker, if any


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


def derive_trace_tokens(spans: Iterable[GenAISpan], tolerance: float = 0.02) -> dict:
    spans = list(spans)
    if not spans:
        raise UnaccountableTraceError("empty trace: no spans to account")

    roots = [s for s in spans if s.parent_id is None]
    if len(roots) != 1:
        raise UnaccountableTraceError(
            f"expected exactly one root span, found {len(roots)}"
        )
    root = roots[0]
    by_id = {s.span_id: s for s in spans}

    # Closure: every span must end at or before the root's end_time.
    late = [s.span_id for s in spans if s.end_time_ns > root.end_time_ns]
    if late:
        raise UnaccountableTraceError(
            f"span closure violated: {late} end after root {root.span_id}"
        )

    # Response-emitting spans: inference ops, plus any tool span carrying usage.
    emitters = [
        s for s in spans
        if s.operation in INFERENCE_OPS
        or (s.operation == "execute_tool" and s.input_tokens is not None)
    ]
    if not emitters:
        raise UnaccountableTraceError("no response-emitting spans with usage found")

    missing = [s.span_id for s in emitters if s.input_tokens is None or s.output_tokens is None]
    if missing:
        # Leaves are incomplete: re-derivation under-counts and the parent
        # is a single-response claim. Neither is defensible.
        raise UnaccountableTraceError(
            f"usage attributes missing on response-emitting spans: {missing}"
        )

    leaf_in = sum(s.input_tokens for s in emitters)
    leaf_out = sum(s.output_tokens for s in emitters)

    # Cross-check against an explicit aggregator, if the root claims one.
    if root.aggregation == "subtree_sum":
        if root.input_tokens is None or root.output_tokens is None:
            raise UnaccountableTraceError(
                "root claims subtree_sum aggregation but lacks usage attributes"
            )
        denom = max(leaf_in, 1)
        drift = abs(root.input_tokens - leaf_in) / denom
        if drift > tolerance:
            raise UnaccountableTraceError(
                f"aggregator drift {drift:.3f} exceeds tolerance {tolerance}: "
                f"root={root.input_tokens} leaves={leaf_in} — suspect lost or "
                f"double-counted descendant, replay required"
            )

    models = {s.response_model for s in emitters if s.response_model}
    if root.response_model and len(models) > 1:
        # Root provenance is a single-response claim; do not flatten.
        provenance = "heterogeneous"
    else:
        provenance = root.response_model or "unknown"

    return {
        "input_tokens": leaf_in,
        "output_tokens": leaf_out,
        "provenance": provenance,
        "models_seen": sorted(models),
        "source": "leaf_rederivation",
    }
