# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-span-graphs-from-silently-orphaning-tool-call-edges-across-multi-turn-agent-invocations.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-span-graphs-from-silently-orphaning-tool-call-edges-across-multi-turn-agent-invocations.warrant.json
# Markdown SHA-256:   4d7ac5c05717965b3007ff447c0a5006f94015a2b7e0da30a942d120b61a1b82
# Code AST SHA-256:   ddc3c2aa5e9ee094a80985330f8269dc084777d33566edb689d2aa547b265a82
# Verified Classes:   SpanGraphInvariantError, SpanRecord, ConversationSpanRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class SpanGraphInvariantError(RuntimeError):
    """Raised when a resumed agent turn would violate tool-call edge invariants."""


@dataclass
class SpanRecord:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    operation_name: str
    tool_call_id: Optional[str] = None
    replayed: bool = False


@dataclass
class ConversationSpanRegistry:
    """Per-conversation registry enforcing exactly-once tool-call edges."""

    conversation_id: str
    live_span_ids: set[str] = field(default_factory=set)
    emitted_tool_calls: dict[str, str] = field(default_factory=dict)  # call_id -> turn root span_id
    prior_turn_roots: list[str] = field(default_factory=list)

    def open_turn_root(self, trace_id: str, span_id: str) -> SpanRecord:
        record = SpanRecord(
            trace_id=trace_id,
            span_id=span_id,
            parent_span_id=None,
            operation_name="invoke_agent",
        )
        self.live_span_ids.add(span_id)
        return record

    def close_turn_root(self, span_id: str) -> None:
        self.live_span_ids.discard(span_id)
        self.prior_turn_roots.append(span_id)

    def emit_tool_call(
        self,
        trace_id: str,
        span_id: str,
        parent_span_id: str,
        tool_call_id: str,
        tool_name: str,
    ) -> SpanRecord:
        # Invariant 1: parent must be a live span in this process context.
        if parent_span_id not in self.live_span_ids:
            raise SpanGraphInvariantError(
                f"tool span {span_id} parent {parent_span_id} is not live; "
                f"cannot synthesize parentage from serialized transcript "
                f"(conversation={self.conversation_id})"
            )
        # Invariant 2: exactly-once emission per tool_call_id per conversation.
        if tool_call_id in self.emitted_tool_calls:
            prior_root = self.emitted_tool_calls[tool_call_id]
            raise SpanGraphInvariantError(
                f"tool_call_id {tool_call_id} already emitted under turn root "
                f"{prior_root}; replayed results must be recorded as events, "
                f"not re-emitted execute_tool spans "
                f"(conversation={self.conversation_id})"
            )
        self.emitted_tool_calls[tool_call_id] = parent_span_id
        return SpanRecord(
            trace_id=trace_id,
            span_id=span_id,
            parent_span_id=parent_span_id,
            operation_name="execute_tool",
            tool_call_id=tool_call_id,
        )

    def record_replayed_tool_result(
        self, tool_call_id: str, originating_turn_root: str
    ) -> SpanRecord:
        """Replay is expressed as an event on the new turn, linked (not parented)."""
        if tool_call_id not in self.emitted_tool_calls:
            raise SpanGraphInvariantError(
                f"replay of unknown tool_call_id {tool_call_id}; "
                f"conversation {self.conversation_id} has no originating span"
            )
        return SpanRecord(
            trace_id="",
            span_id="",
            parent_span_id=None,
            operation_name="gen_ai.tool.result.replayed",
            tool_call_id=tool_call_id,
            replayed=True,
        )
