# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-span-parent-corruption-when-opentelemetry-genai-tool-call-graphs-are-reconstructed-across-agent-re-entrancy.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-span-parent-corruption-when-opentelemetry-genai-tool-call-graphs-are-reconstructed-across-agent-re-entrancy.warrant.json
# Markdown SHA-256:   9060a0d87c9df6771f4454560c95845a282732389d2df428cdf0a4b3ec7d4e73
# Code AST SHA-256:   00afbe56ae89e7ed3e6c09c79ff45db2048411ca203540671341642b46d75ba7
# Verified Classes:   SpanParentCorruption, ToolCheckpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class SpanParentCorruption(RuntimeError):
    """Raised when a resumed tool span cannot be soundly parented."""
    pass


@dataclass(frozen=True)
class ToolCheckpoint:
    trace_id: str
    requesting_span_id: str   # the chat span that decided the tool call
    tool_name: str
    call_index: int

    def idempotency_key(self) -> str:
        return f"{self.trace_id}:{self.requesting_span_id}:{self.tool_name}:{self.call_index}"


def emit_resumed_tool_span(
    checkpoint: ToolCheckpoint,
    ambient_parent_span_id: str | None,
    known_span_ids: set[str],
    emitted_keys: set[str],
) -> dict:
    # Invariant 1: parent must come from the checkpoint, not ambient context.
    if ambient_parent_span_id is not None and ambient_parent_span_id != checkpoint.requesting_span_id:
        raise SpanParentCorruption(
            f"ambient parent {ambient_parent_span_id} != persisted parent "
            f"{checkpoint.requesting_span_id}; refusing to mis-parent {checkpoint.tool_name}"
        )

    # Invariant 2: the persisted parent must still exist in the trace.
    if checkpoint.requesting_span_id not in known_span_ids:
        raise SpanParentCorruption(
            f"persisted parent {checkpoint.requesting_span_id} evicted from trace "
            f"{checkpoint.trace_id}; cannot attach {checkpoint.tool_name}"
        )

    # Invariant 3: idempotency key prevents timeout/resume double-emit.
    key = checkpoint.idempotency_key()
    if key in emitted_keys:
        raise SpanParentCorruption(
            f"duplicate emission for {key}; tool call already recorded"
        )

    emitted_keys.add(key)
    return {
        "name": f"execute_tool {checkpoint.tool_name}",
        "trace_id": checkpoint.trace_id,
        "parent_span_id": checkpoint.requesting_span_id,  # explicit, from checkpoint
        "attributes": {
            "gen_ai.operation.name": "execute_tool",
            "gen_ai.tool.name": checkpoint.tool_name,
            "gen_ai.agent.id": checkpoint.trace_id,
        },
    }
