# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-anchor-its-trace-context-when-an-otel-span-parent-is-a-sibling-agent-s-llm-turn.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-anchor-its-trace-context-when-an-otel-span-parent-is-a-sibling-agent-s-llm-turn.warrant.json
# Markdown SHA-256:   791d4e72c21dd3238108473a2d3a411580f7b82d77891d2d3c28113b4abf7c1f
# Code AST SHA-256:   a7d491560e8b3256620f0a4d327b09766b84e7f93f5a2ef94cd35e0291f5930b
# Verified Classes:   MisAnchoredTraceError, SpanContextView
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class MisAnchoredTraceError(RuntimeError):
    """Raised when a received task is parented to a span the receiver does not own."""


@dataclass
class SpanContextView:
    trace_id: str
    span_id: str
    owner_instance: str
    is_open: bool


def reanchor_on_receive(
    incoming: SpanContextView,
    receiver_instance: str,
    receiver_active_span_owner: str | None,
) -> SpanContextView:
    # The receiver may only parent to a span it owns and that is still open.
    owns_parent = receiver_active_span_owner == receiver_instance
    if incoming.owner_instance == receiver_instance and incoming.is_open and owns_parent:
        return incoming

    if incoming.owner_instance != receiver_instance:
        # Cross-instance handoff: the sender's span must become a Link, and the
        # receiver must mint its own handoff.receive span as the new parent.
        if incoming.is_open:
            # Sender span still open across the boundary is itself suspect:
            # it means the sender blocked on the receiver, contradicting the
            # async handoff contract. Refuse rather than silently re-parent.
            raise MisAnchoredTraceError(
                f"sender span {incoming.span_id} from {incoming.owner_instance} "
                f"is still open at receive; async handoff violated"
            )
        return SpanContextView(
            trace_id=incoming.trace_id,
            span_id=f"handoff.receive::{receiver_instance}",
            owner_instance=receiver_instance,
            is_open=True,
        )

    if not owns_parent:
        raise MisAnchoredTraceError(
            f"receiver {receiver_instance} attempted to parent to "
            f"span {incoming.span_id} owned by {incoming.owner_instance} "
            f"without an owned active span"
        )

    raise MisAnchoredTraceError(
        f"unhandled anchoring case for span {incoming.span_id}"
    )
