# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-tool-call-spans-from-silently-collapsing-parent-child-causality-during-concurrent-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-tool-call-spans-from-silently-collapsing-parent-child-causality-during-concurrent-fan-out.warrant.json
# Markdown SHA-256:   e30554de15d01e7488827c8ce76d850f381bf487be3e5c02a0bab7ea8951af02
# Code AST SHA-256:   fce4522a8652af396c4e31e43bf489fc624e8783e215d5fd243694c9513dd2be
# Verified Classes:   TemporalContainmentViolation, Span, AgentSpanGuard
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Dict, List


class TemporalContainmentViolation(RuntimeError):
    """Raised when a parent agent span would close before a child tool span it issued."""
    pass


@dataclass
class Span:
    name: str
    span_id: str
    parent_span_id: str | None
    start_time: float
    end_time: float | None = None
    children: List["Span"] = field(default_factory=list)


class AgentSpanGuard:
    """
    Enforces the OTel GenAI invariant: an `invoke_agent` span's end_time
    must be >= max(end_time) over all `execute_tool` children it directly issued.
    Either extend the parent to the child-close barrier, or raise.
    """

    def __init__(self) -> None:
        self._open: Dict[str, Span] = {}

    def open_agent(self, span: Span) -> None:
        self._open[span.span_id] = span

    def register_child(self, parent_id: str, child: Span) -> None:
        if parent_id not in self._open:
            # Parent already closed: this is the fire-and-forget case and must
            # be re-parented to a continuation span, never linked as a child.
            raise TemporalContainmentViolation(
                f"tool span {child.name!r} issued against already-closed agent "
                f"span {parent_id!r}; re-parent to a continuation span or link."
            )
        self._open[parent_id].children.append(child)

    def close_agent(self, parent_id: str, now: float, *, extend_to_barrier: bool = True) -> Span:
        parent = self._open.get(parent_id)
        if parent is None:
            raise TemporalContainmentViolation(f"unknown agent span {parent_id!r}")

        live = [c for c in parent.children if c.end_time is None]
        if live:
            names = ", ".join(c.name for c in live)
            raise TemporalContainmentViolation(
                f"agent span {parent_id!r} closing with {len(live)} live child "
                f"tool span(s) [{names}]; close the child-close barrier first."
            )

        if parent.children:
            barrier = max(c.end_time for c in parent.children)  # type: ignore[type-var]
            if now < barrier:
                if not extend_to_barrier:
                    raise TemporalContainmentViolation(
                        f"agent span {parent_id!r} end_time {now:.3f} precedes child "
                        f"barrier {barrier:.3f}; interval containment broken."
                    )
                now = barrier

        parent.end_time = now
        del self._open[parent_id]
        return parent


def assert_containment(parent: Span) -> None:
    if parent.end_time is None:
        raise TemporalContainmentViolation(f"span {parent.name!r} never closed")
    for child in parent.children:
        if child.end_time is None:
            raise TemporalContainmentViolation(f"child {child.name!r} never closed")
        if child.start_time < parent.start_time or child.end_time > parent.end_time:
            raise TemporalContainmentViolation(
                f"child {child.name!r} interval [{child.start_time:.3f},{child.end_time:.3f}] "
                f"not contained in parent [{parent.start_time:.3f},{parent.end_time:.3f}]"
            )
