# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-an-opentelemetry-genai-span-that-closes-a-tool-call-child-before-its-parent-agent-turn-span-and-how-does-the-invariant-s.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-an-opentelemetry-genai-span-that-closes-a-tool-call-child-before-its-parent-agent-turn-span-and-how-does-the-invariant-s.warrant.json
# Markdown SHA-256:   90e700959c88471f76ba42ad6d5f78e342dfc5163706f17b86c5a63fc7e9721c
# Code AST SHA-256:   932e9f03b4c3c8f04c833f376c2b81c26d59e3f5eeda3389aace18c3108f3b98
# Verified Classes:   SpanReemissionError, TurnSpanRegistry
# Defensive Guards:   8 fail-closed invariants (zero external deps)

class SpanReemissionError(RuntimeError):
    """Raised when a runtime attempts to re-emit an already-ended span or
    emit a tool-call child whose parent turn span was never closed."""
    pass


class TurnSpanRegistry:
    """Enforces the causal closure invariant for GenAI agent-turn traces:
    one turn span per logical turn, ended exactly once; tool children are
    emitted once and never re-parented or re-emitted across retries."""

    def __init__(self):
        self._open_turns = {}      # logical_turn_id -> span
        self._emitted_span_ids = set()
        self._emitted_children = set()  # (logical_turn_id, tool_call_id)

    def open_turn(self, logical_turn_id, span):
        if logical_turn_id in self._open_turns:
            # Retry path tried to fork a new turn span for the same logical turn.
            raise SpanReemissionError(
                f"turn {logical_turn_id} already open; retries must reuse the "
                f"existing span, not open a new one"
            )
        self._open_turns[logical_turn_id] = span
        return span

    def emit_tool_child(self, logical_turn_id, tool_call_id, child_span):
        if logical_turn_id not in self._open_turns:
            raise SpanReemissionError(
                f"tool child {tool_call_id} emitted for turn {logical_turn_id} "
                f"with no open parent turn span"
            )
        key = (logical_turn_id, tool_call_id)
        if key in self._emitted_children:
            # Cached tool span being re-emitted on retry.
            raise SpanReemissionError(
                f"tool child {tool_call_id} already emitted for turn "
                f"{logical_turn_id}; record cached result as attribute, "
                f"do not re-emit span"
            )
        if child_span.span_id in self._emitted_span_ids:
            raise SpanReemissionError(
                f"span_id {child_span.span_id} already emitted in this trace"
            )
        parent = self._open_turns[logical_turn_id]
        if child_span.parent_span_id != parent.span_id:
            raise SpanReemissionError(
                f"tool child parent_span_id {child_span.parent_span_id} does not "
                f"match open turn span_id {parent.span_id}"
            )
        self._emitted_children.add(key)
        self._emitted_span_ids.add(child_span.span_id)
        return child_span

    def close_turn(self, logical_turn_id, span, terminal: bool):
        """End the turn span exactly once. Non-terminal errors (e.g. token-budget
        exhaustion followed by retry) must NOT close the turn."""
        if logical_turn_id not in self._open_turns:
            raise SpanReemissionError(
                f"close_turn called for {logical_turn_id} which is not open"
            )
        if self._open_turns[logical_turn_id] is not span:
            raise SpanReemissionError(
                f"close_turn span identity mismatch for {logical_turn_id}"
            )
        if not terminal:
            # Retry follows: keep the turn span open, do not end it.
            return
        if span.span_id in self._emitted_span_ids:
            raise SpanReemissionError(
                f"turn span_id {span.span_id} already emitted"
            )
        self._emitted_span_ids.add(span.span_id)
        del self._open_turns[logical_turn_id]
        span.end()
