# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-causal-trace-silently-fork-when-genai-semantic-convention-span-links-cross-an-agent-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-causal-trace-silently-fork-when-genai-semantic-convention-span-links-cross-an-agent-handoff.warrant.json
# Markdown SHA-256:   00e082cbf72714fcd88128b4b9b28720a7f5a3b62a6a554c9281bd317da8c541
# Code AST SHA-256:   b1e74732d1ebe9b6598afde8b6c6354b4667c341def080899d848aedc0cff5ea
# Verified Classes:   CausalTraceForkError, SpanContext
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import uuid
from dataclasses import dataclass, field


class CausalTraceForkError(RuntimeError):
    """Raised when an agent handoff would silently fork the causal trace."""


@dataclass
class SpanContext:
    trace_id: str
    span_id: str
    conversation_id: str
    causal_root_id: str
    links: list = field(default_factory=list)


def handoff(
    sender: SpanContext,
    receiver_tenant: str,
    incoming_payload: dict,
    sampler_keeps_linked: bool,
) -> SpanContext:
    """Propagate causality across an agent boundary without forking the trace."""
    link_trace = incoming_payload.get("trace_id")
    link_span = incoming_payload.get("span_id")
    root = incoming_payload.get("causal_root_id")

    # Invariant 1: link target must be present and well-formed.
    if not link_trace or not link_span:
        raise CausalTraceForkError(
            f"handoff from {sender.span_id} carries no resolvable link target; "
            "receiver would root a new trace silently"
        )
    if link_trace != sender.trace_id or link_span != sender.span_id:
        raise CausalTraceForkError(
            f"link target {link_trace}/{link_span} does not match sender "
            f"{sender.trace_id}/{sender.span_id}; causality payload corrupted"
        )

    # Invariant 2: causal root must be carried, not inferred from trace_id.
    if not root:
        raise CausalTraceForkError(
            "missing causal_root_id; a trace_id change would orphan this span "
            "from the root under link-drop sampling"
        )

    # Invariant 3: sampler must preserve linked spans or the link is severed.
    if not sampler_keeps_linked:
        raise CausalTraceForkError(
            "tail sampler is not link-preserving; linked span may be dropped "
            "while this span is kept, yielding a dangling link"
        )

    # Invariant 4: conversation id must be tenant-scoped.
    if not sender.conversation_id.startswith(receiver_tenant + ":"):
        raise CausalTraceForkError(
            f"conversation_id {sender.conversation_id!r} not scoped to tenant "
            f"{receiver_tenant!r}; secondary join can cross trust boundaries"
        )

    return SpanContext(
        trace_id=str(uuid.uuid4()),          # receiver gets its own trace...
        span_id=str(uuid.uuid4()),
        conversation_id=sender.conversation_id,
        causal_root_id=root,                 # ...but shares the causal root
        links=[{"trace_id": link_trace, "span_id": link_span}],
    )
