# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-trace-parent-join-across-a-mesh-as-unsound-and-how-does-the-span-context-rebinding-invariant-prevent-si.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-trace-parent-join-across-a-mesh-as-unsound-and-how-does-the-span-context-rebinding-invariant-prevent-si.warrant.json
# Markdown SHA-256:   30dd4a1b33533dfe8798a129e2b72aebd8edc43a4e4152aebd2a1b9f192a864b
# Code AST SHA-256:   6baf623a2766666e9e966f53520c4f40d286c5922bf012387521c60d562529ac
# Verified Classes:   UnsoundTraceParentJoin, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class UnsoundTraceParentJoin(RuntimeError):
    """Raised when a span cannot be causally joined to its parent across a mesh boundary."""
    pass


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    parent_trace_id: str | None      # carried attribute, may be None if header stripped
    parent_span_id: str | None
    handoff_nonce: str | None        # 128-bit random, minted at handoff
    fork_reason: str | None = None   # set only for intentional safety-plane forks


def rebind_and_join(child: Span, known_nonces: set[str]) -> str:
    """
    Return the authoritative trace_id that the child should be indexed under.

    Invariant (V1-V4): a cross-boundary span is causally joinable ONLY via the
    carried (parent_trace_id, parent_span_id, handoff_nonce) tuple. trace_id
    equality is a hint, never a proof.
    """
    # Case 1: same trace_id AND carried tuple agrees -> trusted inheritance.
    if child.parent_trace_id is None and child.handoff_nonce is None:
        # No carried context. Only sound if the child did NOT re-parent.
        # We cannot verify that here, so we must refuse to assert causality.
        raise UnsoundTraceParentJoin(
            f"span {child.span_id} in trace {child.trace_id} carries no mesh context; "
            "cannot distinguish trusted inheritance from silent re-parenting"
        )

    # Case 2: carried context present -> must validate the nonce (V2).
    if child.handoff_nonce is None:
        raise UnsoundTraceParentJoin(
            f"span {child.span_id} carries parent_trace_id={child.parent_trace_id} "
            "but no handoff_nonce; nonce is mandatory across a trust boundary (V2)"
        )
    if child.handoff_nonce not in known_nonces:
        # Nonce not minted by any parent we know about -> fabricated or replayed edge.
        raise UnsoundTraceParentJoin(
            f"span {child.span_id} presents nonce {child.handoff_nonce!r} "
            "that no parent minted; refusing to fabricate a causal edge"
        )

    # Case 3: intentional fork (V4) is allowed but must be labeled.
    if child.trace_id != child.parent_trace_id and child.fork_reason is None:
        # Re-parented without declaring a fork -> would orphan safety events.
        raise UnsoundTraceParentJoin(
            f"span {child.span_id} re-parented from {child.parent_trace_id} to "
            f"{child.trace_id} with no fork_reason; safety events would be orphaned (V4)"
        )

    # Sound: index under the parent trace so safety events remain reachable.
    return child.parent_trace_id


def index_safety_event(event_span: Span, known_nonces: set[str]) -> str:
    """Safety events MUST be anchored to the reachable parent trace (V3)."""
    authoritative = rebind_and_join(event_span, known_nonces)
    if authoritative is None:
        raise UnsoundTraceParentJoin(
            f"safety event {event_span.span_id} has no reachable parent trace; "
            "it would be invisible to entry-point audits"
        )
    return authoritative
