# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-genai-agent-span-whose-tool-call-attributes-were-re-parented-across-a-model-invocation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-genai-agent-span-whose-tool-call-attributes-were-re-parented-across-a-model-invocation-boundary.warrant.json
# Markdown SHA-256:   e7ac4f0b20713494bacd994289078b062d669759b4a163675e6c0fefed92e631
# Code AST SHA-256:   be9d7af86d958a68aaf99f0addebd23b79ad25f01cfaf2f42328c4cc30cc9c6e
# Verified Classes:   GenAISpanInvariantError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class GenAISpanInvariantError(RuntimeError):
    """Raised when a GenAI span violates the 1:1 model-invocation invariant."""


@dataclass
class GenAISpan:
    span_id: str
    parent_span_id: str | None
    operation_name: str                      # "chat" | "tool.call" | "agent"
    usage_input_tokens: int | None = None
    usage_output_tokens: int | None = None
    usage_write_count: int = 0               # increments each set_attribute
    tool_name: str | None = None
    tool_call_id: str | None = None
    finish_reason: str | None = None
    children: list["GenAISpan"] = field(default_factory=list)


def validate_genai_span(span: GenAISpan) -> None:
    """Enforce the per-invocation usage invariant and tool parentage coherence."""

    # Invariant 1: usage attributes are single-writer (no accumulation).
    if span.operation_name == "chat" and span.usage_write_count > 1:
        raise GenAISpanInvariantError(
            f"span {span.span_id}: gen_ai.usage.* written "
            f"{span.usage_write_count} times; usage must be set once per "
            f"model invocation, not accumulated across a tool loop"
        )

    # Invariant 2: a chat span's tool children must be the calls it emitted.
    if span.operation_name == "chat":
        tool_children = [c for c in span.children if c.operation_name == "tool.call"]
        if len(tool_children) > 1 and span.finish_reason != "tool_calls":
            raise GenAISpanInvariantError(
                f"span {span.span_id}: {len(tool_children)} tool.call children "
                f"but finish_reason={span.finish_reason!r}; loop was collapsed "
                f"into a single model-invocation span"
            )
        for child in tool_children:
            if not child.tool_call_id:
                raise GenAISpanInvariantError(
                    f"tool span {child.span_id} under {span.span_id} missing "
                    f"gen_ai.tool.call.id; cannot verify parentage"
                )

    # Invariant 3: no tool span may outlive a re-opened parent (retry orphan).
    for child in span.children:
        if child.parent_span_id != span.span_id:
            raise GenAISpanInvariantError(
                f"tool span {child.span_id} claims parent "
                f"{child.parent_span_id!r} but is nested under {span.span_id}; "
                f"re-parented across a retry boundary"
            )


def normalize_turn_usage(turn_spans: list[GenAISpan]) -> int:
    """Sum input tokens over per-invocation chat spans; reject accumulated spans."""
    total = 0
    for span in turn_spans:
        validate_genai_span(span)
        if span.operation_name == "chat":
            total += span.usage_input_tokens or 0
    return total
