# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-an-opentelemetry-genai-span-tree-loses-causal-ordering-across-an-async-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-an-opentelemetry-genai-span-tree-loses-causal-ordering-across-an-async-tool-call-boundary.warrant.json
# Markdown SHA-256:   62a785f1f2c2a658797d19cda1c5be8dc53beb1f58333f3ec68755ec81f39e27
# Code AST SHA-256:   401d1b3e25c4ae0abe0f28ba77c4492c4987db0555636b7b40648913c25001f2
# Verified Classes:   CausalOrderViolation, GenAISpan
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class CausalOrderViolation(RuntimeError):
    """Raised when a GenAI span tree would encode a causal order that never happened."""


@dataclass
class GenAISpan:
    name: str
    operation: str  # gen_ai.operation.name
    parent_id: Optional[str]
    start_time: float
    end_time: Optional[float] = None
    tool_call_id: Optional[str] = None
    attempt: Optional[int] = None
    resume_marker: bool = False


def emit_child_span(parent: GenAISpan, child: GenAISpan, *, checkpoint_resumed: bool) -> GenAISpan:
    """Validate containment and attempt-identity before export.

    Halt if the child would be exported under a parent whose interval does not
    contain it, unless the child is re-parented to an explicit resume marker.
    """
    if child.end_time is None:
        raise CausalOrderViolation(
            f"child span {child.name!r} exported without end_time; cannot verify containment"
        )

    # Containment invariant: start_time(parent) <= start_time(child) and end_time(child) <= end_time(parent)
    if child.start_time < parent.start_time:
        if not checkpoint_resumed or not child.resume_marker:
            raise CausalOrderViolation(
                f"containment violated: child {child.name!r} start {child.start_time} "
                f"precedes parent {parent.name!r} start {parent.start_time} "
                f"without an explicit resume marker"
            )

    if parent.end_time is not None and child.end_time > parent.end_time:
        raise CausalOrderViolation(
            f"containment violated: child {child.name!r} end {child.end_time} "
            f"exceeds parent {parent.name!r} end {parent.end_time}"
        )

    # Attempt identity: a tool call id reused across attempts must carry an explicit attempt number.
    if child.operation == "execute_tool" and child.tool_call_id is not None:
        if child.attempt is None:
            raise CausalOrderViolation(
                f"tool span {child.name!r} with gen_ai.tool.call.id={child.tool_call_id!r} "
                f"lacks gen_ai.tool.attempt; retries are indistinguishable from duplicates"
            )

    return child


def validate_consumption_edge(tool_span: GenAISpan, consumer_span: GenAISpan) -> None:
    """A reasoning step that consumed a tool result must start after that result ended."""
    if tool_span.end_time is None:
        raise CausalOrderViolation(
            f"cannot order consumption: tool span {tool_span.name!r} has no end_time"
        )
    if consumer_span.start_time < tool_span.end_time:
        raise CausalOrderViolation(
            f"precedence violated: consumer {consumer_span.name!r} started at "
            f"{consumer_span.start_time} before tool {tool_span.name!r} ended at "
            f"{tool_span.end_time}; dependency is unencoded and may be a race"
        )
