# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-a-single-trace-root-across-mcp-sessions-a2a-task-boundaries-and-delegated-sub-agents-and-what-silentl.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-a-single-trace-root-across-mcp-sessions-a2a-task-boundaries-and-delegated-sub-agents-and-what-silentl.warrant.json
# Markdown SHA-256:   1dece601d5629293de02ac6e28a5e6324c7ae312fb16b4ffcdee19b4627cc70a
# Code AST SHA-256:   1ea6bce4e4b01d347b48032a5be647ae2563c1a3f425fe9f9a9f1d655ed05c9a
# Verified Classes:   TraceRootViolation, TraceContext, BoundaryState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class TraceRootViolation(RuntimeError):
    """Raised when a downstream component mints or loses a trace root
    instead of propagating the ingress root across a boundary."""


@dataclass(frozen=True)
class TraceContext:
    root_id: str
    parent_span_id: Optional[str]
    origin: str  # "ingress" | "mcp" | "a2a" | "delegation"


@dataclass
class BoundaryState:
    ingress_root: str
    seen_roots: set[str] = field(default_factory=set)


def propagate_across_mcp_initialize(
    state: BoundaryState,
    incoming: Optional[TraceContext],
    session_id: str,
    is_resume: bool,
) -> TraceContext:
    """MCP session establish/resume must carry the root in-band.

    A resume is NOT a new causal origin; it must reuse the ingress root.
    """
    if incoming is None:
        # Downstream work with no propagated root: fail closed, do not mint.
        raise TraceRootViolation(
            f"MCP initialize for session {session_id!r} (resume={is_resume}) "
            "arrived without a trace root; refusing to mint a new tree"
        )
    if incoming.root_id != state.ingress_root:
        raise TraceRootViolation(
            f"MCP session {session_id!r} carried root {incoming.root_id!r} "
            f"but ingress root is {state.ingress_root!r}; a boundary "
            "component minted a divergent root"
        )
    state.seen_roots.add(incoming.root_id)
    return TraceContext(
        root_id=state.ingress_root,
        parent_span_id=incoming.parent_span_id,
        origin="mcp",
    )


def propagate_across_a2a_task(
    state: BoundaryState,
    envelope_root: Optional[str],
    envelope_parent_span: Optional[str],
    task_id: str,
) -> TraceContext:
    """A2A task envelope must carry root + parent span; peer parents under it."""
    if envelope_root is None:
        raise TraceRootViolation(
            f"A2A task {task_id!r} envelope has no root field; peer would "
            "emit a disconnected tree joined only by message-body strings"
        )
    if envelope_root != state.ingress_root:
        raise TraceRootViolation(
            f"A2A task {task_id!r} root {envelope_root!r} != ingress root "
            f"{state.ingress_root!r}; peer minted a fresh root"
        )
    return TraceContext(
        root_id=state.ingress_root,
        parent_span_id=envelope_parent_span,
        origin="a2a",
    )


def join_span(
    state: BoundaryState,
    span_root: str,
    span_parent: Optional[str],
    span_id: str,
    quarantine: list[str],
) -> None:
    """Admissibility: every span must resolve to the ingress root and a parent.

    Unresolvable spans are quarantined, never stitched by heuristic.
    """
    if span_root != state.ingress_root or span_parent is None:
        quarantine.append(span_id)
        raise TraceRootViolation(
            f"span {span_id!r} (root={span_root!r}, parent={span_parent!r}) "
            "cannot be joined to the ingress tree; quarantined, not stitched"
        )
