# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-child-spans-when-an-agent-s-parent-context-is-evicted-mid-trajectory.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-child-spans-when-an-agent-s-parent-context-is-evicted-mid-trajectory.warrant.json
# Markdown SHA-256:   48ebf03bb5f83b249de178f2f601918ab7fefab1d33788b13d62942521f7a0ac
# Code AST SHA-256:   bb8e4dec58494cdd6ba7d9685c860a2758e4ad9951c0a9e31987ecd19689d1de
# Verified Classes:   SpanClosureOrderViolation, GenAISpan, SpanProcessor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass, field
from typing import Optional


class SpanClosureOrderViolation(RuntimeError):
    """Raised when a parent span is ended while it still has open children,
    and no lawful drain-or-adopt transition was performed."""


@dataclass
class GenAISpan:
    span_id: str
    parent_span_id: Optional[str]
    operation: str  # e.g. "invoke_agent", "execute_tool"
    conversation_id: str
    start_time: float = field(default_factory=time.monotonic)
    end_time: Optional[float] = None
    predecessor_span_id: Optional[str] = None
    _open_children: set[str] = field(default_factory=set)

    def register_child(self, child_id: str) -> None:
        if self.end_time is not None:
            raise SpanClosureOrderViolation(
                f"cannot attach child {child_id!r} to already-ended span {self.span_id!r}"
            )
        self._open_children.add(child_id)

    def child_closed(self, child_id: str) -> None:
        self._open_children.discard(child_id)


class SpanProcessor:
    """Enforces the closure-ordering invariant across a checkpoint/resume boundary."""

    def __init__(self, child_timeout_s: float = 30.0) -> None:
        self.child_timeout_s = child_timeout_s
        self._spans: dict[str, GenAISpan] = {}

    def open(self, span: GenAISpan) -> None:
        self._spans[span.span_id] = span
        if span.parent_span_id and span.parent_span_id in self._spans:
            self._spans[span.parent_span_id].register_child(span.span_id)

    def close(self, span_id: str) -> None:
        span = self._spans[span_id]
        span.end_time = time.monotonic()
        if span.parent_span_id and span.parent_span_id in self._spans:
            self._spans[span.parent_span_id].child_closed(span_id)

    def checkpoint(
        self,
        parent_id: str,
        successor: GenAISpan,
        policy: str = "drain",
    ) -> None:
        parent = self._spans[parent_id]
        if parent.end_time is not None:
            return  # already closed; successor just opens fresh

        if parent._open_children and policy == "drain":
            deadline = time.monotonic() + self.child_timeout_s
            while parent._open_children and time.monotonic() < deadline:
                time.sleep(0.01)
            if parent._open_children:
                raise SpanClosureOrderViolation(
                    f"drain timed out for parent {parent_id!r}; "
                    f"{len(parent._open_children)} children still open"
                )
        elif parent._open_children and policy == "adopt":
            successor.predecessor_span_id = parent_id
            for child_id in parent._open_children:
                child = self._spans[child_id]
                child.parent_span_id = successor.span_id
                successor.register_child(child_id)
            parent._open_children.clear()
        elif parent._open_children:
            raise SpanClosureOrderViolation(
                f"ending parent {parent_id!r} with {len(parent._open_children)} "
                f"open children and no drain/adopt transition (policy={policy!r})"
            )

        self.close(parent_id)
        self.open(successor)
