# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-otel-genai-span-trees-from-silently-orphaning-tool-call-attributes-across-agent-retries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-otel-genai-span-trees-from-silently-orphaning-tool-call-attributes-across-agent-retries.warrant.json
# Markdown SHA-256:   b34bd4c31ce43022276e7a08d6f0a731a843919933d79ae87cc6d9aaedcbb339
# Code AST SHA-256:   3a850a3dc9bcd3fa21ee4bbca89b8ab73327081960f025c490e9458bd3fc9f98
# Verified Classes:   OrphanedToolCallError, ToolRequest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class OrphanedToolCallError(RuntimeError):
    """Raised when an execute_tool span cannot be reconciled to a unique anchor span."""


@dataclass(frozen=True)
class ToolRequest:
    conversation_id: str
    tool_call_id: str
    retry_of: Optional[str]
    anchor_span_id: Optional[str]  # captured at enqueue, persisted in checkpoint


def resolve_anchor(req: ToolRequest, known_anchors: dict[tuple[str, str], str]) -> str:
    """
    Reconcile a tool request to exactly one anchor span.

    known_anchors maps (conversation_id, tool_call_id) -> anchor span_id,
    populated at enqueue time while the parent chat/invoke_agent span is open.
    """
    if req.retry_of is not None and req.tool_call_id == req.retry_of:
        # Retry reused the original call id: anchor resolution is ambiguous.
        raise OrphanedToolCallError(
            f"retry for {req.tool_call_id!r} reused the original call id; "
            f"mint a new id and record retry_of={req.retry_of!r}"
        )

    key = (req.conversation_id, req.tool_call_id)
    anchor = req.anchor_span_id or known_anchors.get(key)

    if anchor is None:
        # No anchor captured at enqueue and no registry hit: the child span
        # will be parented to root with correct attributes but no logical edge.
        raise OrphanedToolCallError(
            f"no anchor span for conversation={req.conversation_id!r} "
            f"tool_call={req.tool_call_id!r}; span would orphan on resume"
        )

    stamped = known_anchors.get(key)
    if stamped is not None and stamped != anchor:
        raise OrphanedToolCallError(
            f"conflicting anchors for {key!r}: {stamped!r} vs {anchor!r}"
        )

    return anchor


def emit_tool_span(req: ToolRequest, known_anchors: dict[tuple[str, str], str]) -> dict:
    anchor = resolve_anchor(req, known_anchors)
    return {
        "name": "execute_tool",
        "attributes": {
            "gen_ai.operation.name": "execute_tool",
            "gen_ai.tool.name": req.tool_call_id.split(":")[0],
            "gen_ai.tool.call.id": req.tool_call_id,
            "gen_ai.conversation.id": req.conversation_id,
            "gen_ai.tool.anchor_span_id": anchor,
            "gen_ai.tool.retry_of": req.retry_of,
        },
    }
