# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-tool-spans-when-a-model-emitted-call-id-is-reused-across-a-retry-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-tool-spans-when-a-model-emitted-call-id-is-reused-across-a-retry-boundary.warrant.json
# Markdown SHA-256:   bc7fcf47ef865e3be67fe96b5e6f61aca0cca73207cceef925bb11b00b1c71d2
# Code AST SHA-256:   a25dac2c96de09d4bfdb24ea29106ad4dd660bb348abec742b889f766ba5c2df
# Verified Classes:   SpanLinkCollisionError, SpanRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SpanLinkCollisionError(RuntimeError):
    """Raised when a tool span would be keyed on a model-emitted call ID
    that already exists in the trace under a different logical parent,
    or when no runtime-authoritative discriminator is available."""
    pass


@dataclass
class SpanRegistry:
    # key -> parent_span_id of the span that owns this key
    keys: dict[str, str] = field(default_factory=dict)


def open_tool_span(
    registry: SpanRegistry,
    model_call_id: str,
    parent_span_id: str,
    attempt: Optional[int],
    runtime_uuid: Optional[str] = None,
) -> str:
    """Open a tool execution span, returning the join key to stamp on it.

    Invariant: the returned key must be injective within the trace.
    The model-emitted ID is only trusted when a runtime discriminator
    (runtime_uuid or attempt) is present to disambiguate reuse.
    """
    if runtime_uuid is not None:
        # Preferred: runtime-authoritative key. Model ID is display-only.
        key = f"rt:{runtime_uuid}"
    elif attempt is not None:
        # Acceptable: attempt-scoped namespacing of the model ID.
        key = f"{model_call_id}#a{attempt}"
    else:
        # Unsafe regime: no discriminator. Refuse to emit a joinable span.
        raise SpanLinkCollisionError(
            f"cannot key tool span on model ID {model_call_id!r}: "
            "no runtime_uuid or attempt discriminator; "
            "emitting would risk silent mis-join on retry or fork"
        )

    existing_parent = registry.keys.get(key)
    if existing_parent is not None and existing_parent != parent_span_id:
        # Key already claimed by a different logical parent: reuse detected.
        raise SpanLinkCollisionError(
            f"call key {key!r} already owned by parent {existing_parent!r}, "
            f"attempted reuse under parent {parent_span_id!r}; "
            "namespace by lineage_id or mint a fresh runtime_uuid"
        )

    registry.keys[key] = parent_span_id
    return key
