# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-span-level-token-attribution-to-preserve-trace-tree-integrity-under-opentelemetry-genai-semantics.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-span-level-token-attribution-to-preserve-trace-tree-integrity-under-opentelemetry-genai-semantics.warrant.json
# Markdown SHA-256:   94433774ba6bd7abeb5b97a42d68a01d468e560ebeba026f17616efd3962a24e
# Code AST SHA-256:   e1ab0cd68b21a98d96a6d66e6f017a64817fa15dc5ff199ae9c61de03461ef3d
# Verified Classes:   AttributionInvariantError, GenAISpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class AttributionInvariantError(RuntimeError):
    """Raised when a GenAI span tree would violate one-owner-per-usage-block."""


@dataclass
class GenAISpan:
    name: str
    operation: str  # "chat" | "tool.call"
    input_tokens: int = 0
    output_tokens: int = 0
    attribution: Literal["owner", "inherited", "none"] = "none"
    retry_of: str | None = None
    children: list["GenAISpan"] = field(default_factory=list)


def emit_turn(
    parent: GenAISpan,
    children: list[GenAISpan],
    provider_input_tokens: int,
    provider_output_tokens: int,
    fan_out: bool,
) -> GenAISpan:
    """Stamp usage onto the tree under the one-owner invariant.

    Returns the parent span with attribution resolved. Raises if the
    resulting tree cannot satisfy both attribution and tree-integrity.
    """
    parent.input_tokens = provider_input_tokens
    parent.output_tokens = provider_output_tokens
    parent.attribution = "owner"

    for child in children:
        if child.operation == "tool.call":
            if child.input_tokens or child.output_tokens:
                # A tool span must never carry model usage unless the
                # provider actually billed it separately.
                raise AttributionInvariantError(
                    f"tool span {child.name!r} carries model usage "
                    f"({child.input_tokens}/{child.output_tokens}); "
                    "shared prompt cost belongs to the chat anchor only"
                )
            child.attribution = "inherited" if fan_out else "none"
        else:
            # Nested chat span with its own usage block: it owns it.
            child.attribution = "owner"

        if child.retry_of is not None and child.attribution == "owner":
            raise AttributionInvariantError(
                f"retry span {child.name!r} re-stamped usage; "
                "retries inherit the anchor, never re-own it"
            )
        parent.children.append(child)

    # Validate: exactly one owner per usage block, leaf-sum rule relaxed.
    owners = [s for s in [parent, *children] if s.attribution == "owner"]
    if len(owners) != 1:
        raise AttributionInvariantError(
            f"expected exactly one usage owner, found {len(owners)}: "
            f"{[s.name for s in owners]}"
        )
    return parent
