# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tool-call-span-collapse-when-genai-semantic-conventions-meet-retried-streamed-and-nested-agent-invocations.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tool-call-span-collapse-when-genai-semantic-conventions-meet-retried-streamed-and-nested-agent-invocations.warrant.json
# Markdown SHA-256:   ad8d361a357d00d47cb84135769510e1d289cc4d71680a79a8ab30f83ab77fc2
# Code AST SHA-256:   6d695f55231b253521746e7a22d2f0116b749797bceb4828611b0f67c6e5a433
# Verified Classes:   SpanCollapseError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SpanCollapseError(RuntimeError):
    """Raised when a GenAI span violates the one-span-per-logical-call invariant."""


@dataclass
class GenAISpan:
    name: str
    operation: str                      # gen_ai.operation.name
    tool_call_id: Optional[str] = None  # gen_ai.tool.call.id
    input_tokens: int = 0               # gen_ai.usage.input_tokens
    output_tokens: int = 0              # gen_ai.usage.output_tokens
    children: list["GenAISpan"] = field(default_factory=list)
    status_code: str = "UNSET"


def validate_before_end(span: GenAISpan) -> None:
    # Invariant 1: a logical span must not carry usage that its children also carry.
    if span.children and (span.input_tokens or span.output_tokens):
        raise SpanCollapseError(
            f"span {span.name!r} carries usage {span.input_tokens}/{span.output_tokens} "
            f"AND {len(span.children)} child attempts; hierarchical topology forbids "
            f"parent-level usage (double-count risk on rollup)."
        )

    # Invariant 2: every child attempt must have a distinct tool_call_id.
    child_ids = [c.tool_call_id for c in span.children if c.tool_call_id]
    if len(child_ids) != len(set(child_ids)):
        raise SpanCollapseError(
            f"span {span.name!r} has duplicate gen_ai.tool.call.id across attempts "
            f"{child_ids}; retries must mint fresh IDs or backend aggregation will merge them."
        )

    # Invariant 3: a streamed partial (no finish_reason) must be ERROR, not UNSET.
    for child in span.children:
        if child.status_code == "UNSET" and child.output_tokens == 0 and child.input_tokens > 0:
            raise SpanCollapseError(
                f"attempt {child.tool_call_id!r} billed {child.input_tokens} input tokens "
                f"but emitted no finish_reason and status UNSET; partial-stream tokens "
                f"must be recorded as ERROR to survive retry reconciliation."
            )

    # Invariant 4: nested agent must not inherit parent tool_call_id unchanged.
    if span.operation == "invoke_agent" and span.tool_call_id in child_ids:
        raise SpanCollapseError(
            f"nested agent {span.name!r} reused parent gen_ai.tool.call.id "
            f"{span.tool_call_id!r}; delegation must mint a fresh correlation ID."
        )


def emit(span: GenAISpan) -> None:
    for child in span.children:
        emit(child)
    validate_before_end(span)
    # span.end() only reached when invariant holds
