# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-opentelemetry-genai-spans-whose-tool-call-attributes-are-re-parented-across-an-async-handoff-silently-breaking-tok.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-opentelemetry-genai-spans-whose-tool-call-attributes-are-re-parented-across-an-async-handoff-silently-breaking-tok.warrant.json
# Markdown SHA-256:   b3bcdc703d0fe45296a836d2b87e5d62c0334857e0a2c0ca2092d8deb7ea0abe
# Code AST SHA-256:   c8445f6f56332b7dc9a4656471080d5acf821adaf60ca282cb4e4fedfdb86dc2
# Verified Classes:   SpanAttributionError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class SpanAttributionError(RuntimeError):
    """Raised when a tool span violates the single-writer usage invariant."""


@dataclass
class Span:
    operation_name: str
    parent_span_id: str | None
    attributes: dict


def validate_tool_span(span: Span) -> None:
    # Invariant 1: a tool span must be a child of an inference span, never a root.
    if span.operation_name == "execute_tool" and span.parent_span_id is None:
        raise SpanAttributionError(
            f"tool span {span.attributes.get('gen_ai.tool.name')!r} has no parent; "
            "context was not propagated across the async handoff"
        )

    # Invariant 2: usage/cost attributes are single-writer, on the chat span only.
    if span.operation_name == "execute_tool":
        leaked = [k for k in span.attributes if k.startswith("gen_ai.usage.")]
        if leaked:
            raise SpanAttributionError(
                f"tool span carries usage attributes {leaked}; "
                "these belong on the parent chat span and will double-count cost"
            )


def aggregate_cost(spans: list[Span]) -> int:
    total = 0
    for span in spans:
        validate_tool_span(span)
        if span.operation_name == "chat":
            total += span.attributes.get("gen_ai.usage.output_tokens", 0)
    return total
