# 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-correlate-the-orphaned-gen-ai-tool-call-id-invariant-under-parallel-agent-fan-ou.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-genai-tool-call-span-it-cannot-correlate-the-orphaned-gen-ai-tool-call-id-invariant-under-parallel-agent-fan-ou.warrant.json
# Markdown SHA-256:   d9af5f8af70e1ce6f9c58e252acd3e337a4b41bd70a06779ca7d07755278e8f9
# Code AST SHA-256:   9c23f851d24c0d2cddf04b5a6df9ab07fa2d2f7ef66118a0249038b8ebd13f99
# Verified Classes:   OrphanedToolCallIdError, ToolCallSpan, TraceIdRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class OrphanedToolCallIdError(RuntimeError):
    """Raised when a tool-call span cannot be uniquely correlated within a trace."""
    pass


@dataclass
class ToolCallSpan:
    trace_id: str
    parent_span_id: str
    agent_name: str
    tool_name: str
    call_id: str | None
    collision: bool = False
    raw_id: str | None = None


class TraceIdRegistry:
    """Enforces (trace_id, gen_ai.tool.call.id) -> exactly one emitted span."""

    def __init__(self) -> None:
        self._claimed: dict[tuple[str, str], str] = {}

    def mint(self, trace_id: str, parent_span_id: str, tool_name: str, nonce: str) -> str:
        # Mint AFTER the invoke decision, scoped to the emitting instance.
        digest = hashlib.sha256(
            f"{trace_id}:{parent_span_id}:{tool_name}:{nonce}".encode()
        ).hexdigest()[:12]
        return f"call_{digest}"

    def claim(self, trace_id: str, call_id: str, parent_span_id: str) -> None:
        key = (trace_id, call_id)
        if key in self._claimed:
            raise OrphanedToolCallIdError(
                f"call_id {call_id!r} in trace {trace_id!r} already claimed by "
                f"parent {self._claimed[key]!r}; emitting instance {parent_span_id!r} "
                f"cannot satisfy the uniqueness invariant"
            )
        self._claimed[key] = parent_span_id


def emit_tool_call_span(
    registry: TraceIdRegistry,
    trace_id: str,
    parent_span_id: str,
    agent_name: str,
    tool_name: str,
    inherited_call_id: str | None,
    nonce: str,
) -> ToolCallSpan:
    """Emit a correlated span, degrade honestly, or refuse when ownership is unknowable."""
    if inherited_call_id is not None:
        # A plan-time inherited id may already be claimed by a sibling worker.
        try:
            registry.claim(trace_id, inherited_call_id, parent_span_id)
        except OrphanedToolCallIdError:
            # We know the id is taken but not who owns the *effect* of our call.
            # Refuse rather than emit a degraded span with a possibly-wrong parent.
            raise OrphanedToolCallIdError(
                f"cannot prove ownership of effect for inherited id "
                f"{inherited_call_id!r} on parent {parent_span_id!r}; refusing span"
            )
        return ToolCallSpan(
            trace_id=trace_id,
            parent_span_id=parent_span_id,
            agent_name=agent_name,
            tool_name=tool_name,
            call_id=inherited_call_id,
        )

    # Fresh mint scoped to this instance; uniqueness by construction.
    call_id = registry.mint(trace_id, parent_span_id, tool_name, nonce)
    registry.claim(trace_id, call_id, parent_span_id)
    return ToolCallSpan(
        trace_id=trace_id,
        parent_span_id=parent_span_id,
        agent_name=agent_name,
        tool_name=tool_name,
        call_id=call_id,
    )


def fan_out_first_tool(registry: TraceIdRegistry, trace_id: str, workers: list[str]) -> list[ToolCallSpan]:
    spans = []
    for i, parent in enumerate(workers):
        spans.append(
            emit_tool_call_span(
                registry,
                trace_id=trace_id,
                parent_span_id=parent,
                agent_name="worker",
                tool_name="http_fetch",
                inherited_call_id="call_7f3a",  # pre-minted at plan time
                nonce=str(i),
            )
        )
    return spans


if __name__ == "__main__":
    reg = TraceIdRegistry()
    try:
        fan_out_first_tool(reg, "trace_abc", ["span_w1", "span_w2", "span_w3"])
    except OrphanedToolCallIdError as exc:
        # Expected: the second worker cannot prove it owns the inherited id.
        print(f"refused: {exc}")
