# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-span-close-ordering-when-a-tool-call-span-outlives-its-parent-agent-turn-the-orphan-span-attribution-failure-in-opent.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-span-close-ordering-when-a-tool-call-span-outlives-its-parent-agent-turn-the-orphan-span-attribution-failure-in-opent.warrant.json
# Markdown SHA-256:   a664e91f4986c187ed4c69f9dad06b314aa5010d77b3e2e490032ad67d61f702
# Code AST SHA-256:   50a3a0d150f33dd0200ac17e5b0f5795bbe987662bd99d6cc7806ea1678887b3
# Verified Classes:   OrphanSpanAttributionError, Span, SpanProcessor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class OrphanSpanAttributionError(RuntimeError):
    """Raised when a parent span closes while child spans remain open."""


@dataclass
class Span:
    name: str
    span_id: str
    parent_id: Optional[str]
    start_time: float
    end_time: Optional[float] = None
    attributes: dict = field(default_factory=dict)
    links: list = field(default_factory=list)


class SpanProcessor:
    def __init__(self, strict: bool = False):
        self.strict = strict
        self.active_children: dict[str, set[str]] = {}
        self.exported: list[Span] = []

    def on_start(self, span: Span) -> None:
        self.active_children.setdefault(span.span_id, set())
        if span.parent_id is not None:
            self.active_children.setdefault(span.parent_id, set()).add(span.span_id)

    def on_end(self, span: Span) -> None:
        if span.end_time is None:
            raise OrphanSpanAttributionError(
                f"span {span.name!r} ended without end_time"
            )
        pending = self.active_children.get(span.span_id, set())
        if pending:
            if self.strict:
                raise OrphanSpanAttributionError(
                    f"span {span.name!r} ({span.span_id}) closed with "
                    f"{len(pending)} open children: {sorted(pending)}"
                )
            # Detach mode: re-parent pending children to trace root,
            # link each back to the closing span.
            for child_id in list(pending):
                child = self._find_active(child_id)
                if child is None:
                    continue
                child.parent_id = None
                child.links.append(
                    {"trace_id": span.attributes.get("trace_id"),
                     "span_id": span.span_id,
                     "relation": "gen_ai.tool.completed_after_turn"}
                )
                child.attributes["gen_ai.tool.completed_after_turn"] = True
        self.active_children.pop(span.span_id, None)
        self.exported.append(span)

    def _find_active(self, span_id: str) -> Optional[Span]:
        for span in self.exported:
            if span.span_id == span_id:
                return span
        return None


def close_turn_span(processor: SpanProcessor, turn: Span,
                    tool_spans: list[Span]) -> None:
    """Close a turn span, enforcing the containment invariant."""
    open_tools = [t for t in tool_spans if t.end_time is None]
    if open_tools:
        # Invariant: turn may not close with open children still parented.
        raise OrphanSpanAttributionError(
            f"turn {turn.name!r} attempted close with {len(open_tools)} "
            f"open tool spans: {[t.name for t in open_tools]}; "
            f"detach or join required before close"
        )
    turn.end_time = max((t.end_time for t in tool_spans), default=turn.start_time)
    processor.on_end(turn)
