# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-a-single-genai-span-for-a-multi-turn-tool-calling-exchange-token-accounting-and-parent-context-divergence-at-the-o.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-a-single-genai-span-for-a-multi-turn-tool-calling-exchange-token-accounting-and-parent-context-divergence-at-the-o.warrant.json
# Markdown SHA-256:   43ad291791838acb8033a67bc299c6f74cd18360a2ab9bb6e4075b1a6de86b29
# Code AST SHA-256:   77edad61cc4673a45e3a4e44cb40543443a88553caf5d5fc3923885c3cbcf8b2
# Verified Classes:   GenAISpanModelingError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class GenAISpanModelingError(RuntimeError):
    """Raised when a GenAI span collapses multiple round-trips or violates temporal/parent invariants."""
    pass

@dataclass
class GenAISpan:
    operation: str                       # e.g. "chat", "execute_tool"
    model: Optional[str]
    input_tokens: int
    output_tokens: int
    finish_reason: Optional[str]
    start_time: float
    end_time: float
    round_index: Optional[int] = None
    parent_round: Optional[int] = None
    child_spans: list = field(default_factory=list)

def validate_chat_span(span: GenAISpan, round_trips: int, models: set) -> None:
    if span.operation != "chat":
        return
    # Invariant 1: token counters must describe exactly one round-trip.
    if round_trips > 1:
        raise GenAISpanModelingError(
            f"chat span aggregates {round_trips} round-trips; token counters "
            f"({span.input_tokens}/{span.output_tokens}) are not attributable to one request. "
            "Decompose into one chat span per round-trip."
        )
    # Invariant 2: a single span cannot honestly name multiple models.
    if len(models) > 1:
        raise GenAISpanModelingError(
            f"chat span names one model but {len(models)} models participated: {sorted(models)}"
        )
    # Invariant 3: no child work may begin after a terminal finish_reason.
    if span.finish_reason in ("tool_calls", "stop"):
        for child in span.child_spans:
            if child.start_time >= span.end_time:
                raise GenAISpanModelingError(
                    f"child span {child.operation!r} starts at {child.start_time} "
                    f">= parent end_time {span.end_time} after finish_reason={span.finish_reason!r}; "
                    "tool work was nested under a finished turn."
                )
    # Invariant 4: multi-agent delegation must link to a specific round.
    if span.child_spans and span.round_index is None:
        raise GenAISpanModelingError(
            "aggregate chat span has children but no round_index; "
            "sub-agent links cannot be resolved to a specific round-trip."
        )
