# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-genai-span-trees-from-misattributing-tool-call-latency-to-the-wrong-turn-in-multi-turn-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-genai-span-trees-from-misattributing-tool-call-latency-to-the-wrong-turn-in-multi-turn-agents.warrant.json
# Markdown SHA-256:   dc737e6c4b1d4633ec6cea39dff6c0794dc49100de539a48c565c016926f7d43
# Code AST SHA-256:   765c8d076097f8bb0818236fc1ce862950ce384c879d1227635b5ee7749f5f37
# Verified Classes:   GenAISpanInvariantError, SpanRecord
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class GenAISpanInvariantError(RuntimeError):
    """Raised when a GenAI tool span violates turn-parenting invariants."""
    pass


@dataclass
class SpanRecord:
    span_id: str
    parent_id: Optional[str]
    operation: str            # e.g. "gen_ai.tool", "gen_ai.chat", "execute_tool"
    tool_name: Optional[str]
    turn_index: Optional[int]
    conversation_id: str
    start_ns: int
    end_ns: int
    resumed: bool = False


def validate_tool_span(span: SpanRecord, parent: Optional[SpanRecord]) -> None:
    if span.operation != "gen_ai.tool":
        return

    if parent is None:
        raise GenAISpanInvariantError(
            f"tool span {span.span_id} has no parent; "
            f"orphan tool spans cannot be attributed to a turn"
        )

    if parent.operation != "gen_ai.chat":
        raise GenAISpanInvariantError(
            f"tool span {span.span_id} ({span.tool_name}) parented to "
            f"{parent.operation} span {parent.span_id}; tool spans must be "
            f"direct children of a gen_ai.chat turn span, not a runtime wrapper"
        )

    if span.turn_index is not None and parent.turn_index is not None:
        if span.turn_index != parent.turn_index:
            raise GenAISpanInvariantError(
                f"tool span {span.span_id} declares turn {span.turn_index} "
                f"but is parented to turn {parent.turn_index}; cross-turn "
                f"tool parenting conflates inter-turn thinking time with "
                f"tool latency"
            )

    if span.end_ns > parent.end_ns:
        raise GenAISpanInvariantError(
            f"tool span {span.span_id} ends at {span.end_ns} after parent "
            f"chat span {parent.span_id} ends at {parent.end_ns}; tool span "
            f"survived the turn boundary and its duration is not a "
            f"tool-latency measurement"
        )

    if span.end_ns < span.start_ns:
        raise GenAISpanInvariantError(
            f"tool span {span.span_id} has negative duration"
        )


def validate_replay_disambiguation(spans: list[SpanRecord]) -> None:
    seen: dict[tuple, list[SpanRecord]] = {}
    for s in spans:
        if s.operation != "gen_ai.tool":
            continue
        key = (s.conversation_id, s.tool_name, s.turn_index)
        seen.setdefault(key, []).append(s)

    for key, group in seen.items():
        if len(group) > 1:
            resumed = [s for s in group if s.resumed]
            if not resumed:
                raise GenAISpanInvariantError(
                    f"duplicate tool spans for {key} with no resumed=true "
                    f"marker; checkpoint replay will double-count duration"
                )
            if len(resumed) == len(group):
                raise GenAISpanInvariantError(
                    f"all spans for {key} marked resumed=true; "
                    f"original emit is missing"
                )
