# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-stitch-a-causal-trace-across-a-missing-span-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-stitch-a-causal-trace-across-a-missing-span-boundary.warrant.json
# Markdown SHA-256:   17967252e891223a09c23d235fac1c771e032a2b1583a06ae1e461a7f7390701
# Code AST SHA-256:   5e1577f1fe7adb313cd485c5554cf5dee6ac885bbff9f67160892e80447b1bd3
# Verified Classes:   TraceStitchError, BoundaryKind, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class TraceStitchError(RuntimeError):
    """Raised when a causal edge cannot be attested and must not be fabricated."""


class BoundaryKind(Enum):
    PROCESS = "process"
    MCP = "mcp"
    A2A = "a2a"


@dataclass
class Span:
    span_id: str
    parent_span_id: str | None
    context_id: str | None
    traceparent: str | None
    boundary: BoundaryKind | None
    correlation_hint: str | None = None


def stitch_child(parent: Span, child: Span) -> str:
    """Return the span_id the child should be attached to, or raise if unattestable."""
    if child.parent_span_id is not None:
        if child.parent_span_id != parent.span_id:
            raise TraceStitchError(
                f"child {child.span_id} attests parent {child.parent_span_id}, "
                f"not {parent.span_id}; refusing to override attestation"
            )
        return parent.span_id

    if child.traceparent is not None:
        return parent.span_id

    # No parent reference and no traceparent. If this crossed a boundary,
    # reparenting to the orchestrator would fabricate an edge.
    if child.boundary is not None:
        raise TraceStitchError(
            f"boundary orphan at {child.boundary.value}: span {child.span_id} "
            f"context_id={child.context_id} has no attested parent; "
            f"quarantine and emit trace.discontinuity, do not attach to root"
        )

    if child.correlation_hint is not None:
        raise TraceStitchError(
            f"foreign-hint orphan: span {child.span_id} offers only free-text "
            f"hint {child.correlation_hint!r}; hints are not causal edges"
        )

    raise TraceStitchError(
        f"unattestable orphan span {child.span_id}; no parent, no traceparent, "
        f"no boundary marker, no hint — cannot classify, must not guess"
    )
