# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-genai-tool-call-span-it-cannot-attribute-to-a-single-model-turn.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-genai-tool-call-span-it-cannot-attribute-to-a-single-model-turn.warrant.json
# Markdown SHA-256:   1a6573bca86311df0d3609619ba95c3b7b5c0900ebced6de8a5128b8e75676fb
# Code AST SHA-256:   c0d6c2a1381f5bf726a4eb5ec3f4ed0190504d2dd5c483b0a3e3185da72b25a6
# Verified Classes:   ToolSpanAttributionError, ChatSpan, ToolSpan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ToolSpanAttributionError(RuntimeError):
    """Raised when a gen_ai execute_tool span cannot be bound to a single model turn."""
    pass


@dataclass
class ChatSpan:
    span_id: str
    call_ids: set[str]
    closed: bool = False


@dataclass
class ToolSpan:
    span_id: str
    call_id: str
    parent_span_id: Optional[str]
    retry_of: Optional[str] = None
    resumed_from_checkpoint: bool = False


def emit_tool_span(
    tool: ToolSpan,
    open_chats: dict[str, ChatSpan],
    known_call_ids: dict[str, str],  # call_id -> owning chat span_id
) -> None:
    # Invariant 1: call_id must be owned by exactly one chat span.
    owner = known_call_ids.get(tool.call_id)
    if owner is not None and owner != tool.parent_span_id:
        raise ToolSpanAttributionError(
            f"call_id {tool.call_id!r} already owned by chat {owner!r}; "
            f"refusing to re-attribute to {tool.parent_span_id!r} without retry_of"
        )
    if owner is not None and tool.retry_of is None and not tool.resumed_from_checkpoint:
        raise ToolSpanAttributionError(
            f"duplicate emit of call_id {tool.call_id!r} with no retry_of marker"
        )

    # Invariant 2: parent chat must be open, or the span must declare a resume.
    parent = open_chats.get(tool.parent_span_id) if tool.parent_span_id else None
    if parent is None:
        if not tool.resumed_from_checkpoint:
            raise ToolSpanAttributionError(
                f"tool span {tool.span_id!r} has no open parent chat "
                f"{tool.parent_span_id!r} and is not a checkpoint resume; "
                "refusing to orphan-promote"
            )
    elif parent.closed:
        raise ToolSpanAttributionError(
            f"parent chat {parent.span_id!r} already closed; "
            "emit as Link, not child"
        )

    # Invariant 3: call_id must be one the parent actually minted.
    if parent is not None and tool.call_id not in parent.call_ids:
        raise ToolSpanAttributionError(
            f"call_id {tool.call_id!r} was not minted by parent chat {parent.span_id!r}"
        )

    known_call_ids.setdefault(tool.call_id, tool.parent_span_id)
    # ... export span here ...
