# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-collapse-at-the-mcp-a2a-boundary-the-orphaned-parent-span-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-collapse-at-the-mcp-a2a-boundary-the-orphaned-parent-span-invariant.warrant.json
# Markdown SHA-256:   5b9121fa460ee09627200f5cafab7678d26a9dfa33b25642a5e3b4744c35b87e
# Code AST SHA-256:   6ed5da824acbecf424013208d86480b7a110468c4dc42b53881536d7bab0db7d
# Verified Classes:   TraceContextCollapseError, SpanContext, OutboundCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TraceContextCollapseError(RuntimeError):
    """Raised when an outbound transport call breaks trace-context continuity
    without emitting an explicit cross-trace link record."""


@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str
    sampled: bool


@dataclass(frozen=True)
class OutboundCall:
    transport: str            # "mcp" | "a2a"
    context: SpanContext
    link_trace_id: Optional[str] = None   # set only when a genuine fork is declared


def assert_context_continuity(inbound: SpanContext, outbound: OutboundCall) -> None:
    """Enforce the orphaned-parent invariant across a transport hop.

    Valid states:
      1. outbound.trace_id == inbound.trace_id  (continued context)
      2. outbound.trace_id != inbound.trace_id AND link_trace_id == inbound.trace_id
         (declared fork, e.g. untrusted external peer)
    Anything else is a silent re-root and must fail loudly.
    """
    continued = outbound.context.trace_id == inbound.trace_id
    declared_fork = (
        outbound.context.trace_id != inbound.trace_id
        and outbound.link_trace_id == inbound.trace_id
    )

    if continued:
        # Sampling decision must be inherited, never re-decided at the hop.
        if outbound.context.sampled != inbound.sampled:
            raise TraceContextCollapseError(
                f"[{outbound.transport}] sampling decision diverged at hop: "
                f"inbound.sampled={inbound.sampled} outbound.sampled={outbound.context.sampled} "
                f"trace_id={inbound.trace_id}"
            )
        return

    if declared_fork:
        return

    raise TraceContextCollapseError(
        f"[{outbound.transport}] trace-context collapse: outbound trace_id "
        f"{outbound.context.trace_id!r} != inbound {inbound.trace_id!r} and no "
        f"link record emitted (link_trace_id={outbound.link_trace_id!r}). "
        f"This severs causal attribution at the MCP/A2A boundary."
    )
