# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-parent-span-whose-genai-conversation-id-was-minted-under-a-different-agent-identity.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-parent-span-whose-genai-conversation-id-was-minted-under-a-different-agent-identity.warrant.json
# Markdown SHA-256:   d2c2d69688a8e7eab0afdb644a0453298988204bd47c791125bf03fb0f5e3591
# Code AST SHA-256:   5093b0511a5a52f8fe345675c3344a8e80c328c23f4bf06f0099934e5d66780d
# Verified Classes:   ConversationIdentityViolation, SpanContext, AgentTracer
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class ConversationIdentityViolation(RuntimeError):
    """Raised when an agent is asked to adopt a parent span context whose
    conversation identity cannot be reconciled with its local binding record."""


@dataclass
class SpanContext:
    trace_id: str
    span_id: str
    conversation_id: Optional[str]
    origin_agent: Optional[str]
    agent_id: str


@dataclass
class AgentTracer:
    agent_id: str
    # conversation.id -> trace.id binding established when this agent first saw it
    _bindings: dict[str, str] = field(default_factory=dict)

    def receive_parent(self, ctx: SpanContext) -> SpanContext:
        if ctx.conversation_id is None:
            # We mint the conversation; we are the origin.
            self._bindings[ctx.conversation_id] = ctx.trace_id
            return ctx

        if ctx.origin_agent is None:
            # Unverifiable origin: emit continuation only, never conversation-defining.
            return SpanContext(
                trace_id=ctx.trace_id,
                span_id=ctx.span_id,
                conversation_id=ctx.conversation_id,
                origin_agent=None,
                agent_id=self.agent_id,
            )

        prior_trace = self._bindings.get(ctx.conversation_id)
        if prior_trace is None:
            # First time we see this conversation; record the binding.
            self._bindings[ctx.conversation_id] = ctx.trace_id
            return ctx

        if prior_trace != ctx.trace_id:
            raise ConversationIdentityViolation(
                f"agent {self.agent_id!r} received conversation "
                f"{ctx.conversation_id!r} bound to trace {ctx.trace_id!r}, "
                f"but locally bound to {prior_trace!r}; refusing to adopt "
                f"parent span {ctx.span_id!r} from origin {ctx.origin_agent!r}"
            )

        return ctx


def handoff(tracer: AgentTracer, parent: SpanContext) -> SpanContext:
    try:
        return tracer.receive_parent(parent)
    except ConversationIdentityViolation:
        # Reject the parent context; emit an orphan span under a fresh trace.
        raise
