# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-the-parent-child-span-cardinality-of-a-single-tool-call-before-genai-semantic-convention-export-or-the-whole-trace-collap.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-the-parent-child-span-cardinality-of-a-single-tool-call-before-genai-semantic-convention-export-or-the-whole-trace-collap.warrant.json
# Markdown SHA-256:   3aa770131e3771692acac63e2cfc4604a9ad37f711e1d2827baec0b884769a44
# Code AST SHA-256:   aee5df94bd11853c2bc68589c17d9487a7487a2c5d2e1722209b17908efc079a
# Verified Classes:   GenAIAttributionError, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class GenAIAttributionError(RuntimeError):
    """Raised when a span batch violates the tool-call attribution invariant."""


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    tool_call_id: Optional[str] = None
    has_usage: bool = False
    has_result_event: bool = False
    attempt: Optional[int] = None
    terminal: bool = False


def validate_tool_attribution(batch: list[Span]) -> None:
    """
    Enforce: for each (parent_span_id, tool_call_id), exactly one terminal
    child may carry usage and result; all others must be demoted with an
    attempt ordinal strictly less than the terminal's.
    """
    groups: dict[tuple[str, str], list[Span]] = {}
    for span in batch:
        if span.tool_call_id is None:
            continue
        key = (span.parent_span_id or "", span.tool_call_id)
        groups.setdefault(key, []).append(span)

    for (parent, call_id), spans in groups.items():
        terminals = [s for s in spans if s.terminal]
        if len(terminals) != 1:
            raise GenAIAttributionError(
                f"call {call_id} under parent {parent}: expected exactly 1 "
                f"terminal span, found {len(terminals)}"
            )
        terminal = terminals[0]
        if not (terminal.has_usage and terminal.has_result_event):
            raise GenAIAttributionError(
                f"call {call_id}: terminal span {terminal.span_id} missing "
                f"usage or result event"
            )
        for s in spans:
            if s is terminal:
                continue
            if s.has_usage or s.has_result_event:
                raise GenAIAttributionError(
                    f"call {call_id}: non-terminal span {s.span_id} carries "
                    f"usage/result; attribution would double-count"
                )
            if s.attempt is None or s.attempt >= (terminal.attempt or 0):
                raise GenAIAttributionError(
                    f"call {call_id}: non-terminal span {s.span_id} lacks a "
                    f"valid attempt ordinal below terminal"
                )


def export_batch(batch: list[Span], exporter) -> None:
    try:
        validate_tool_attribution(batch)
    except GenAIAttributionError:
        # Reject, do not silently export an ambiguous trace.
        raise
    exporter.flush(batch)
