# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-preserve-trace-correlation-when-an-a2a-task-boundary-re-parents-an-mcp-call-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-preserve-trace-correlation-when-an-a2a-task-boundary-re-parents-an-mcp-call-chain.warrant.json
# Markdown SHA-256:   ffd52bee3efad00710cc77689983e64cc7becc08c1654d747adc4fc6765a2370
# Code AST SHA-256:   7aeef535f96008f83af2539b5799821b8ef5a81659648f3c39ec9ddaf0755774
# Verified Classes:   TraceCorrelationError, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TraceCorrelationError(RuntimeError):
    """Raised when an A2A/MCP trace violates the causal-fork invariant."""


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    trace_id: str
    agent_id: str
    name: str
    links: list = field(default_factory=list)


def validate_trace(spans: list[Span]) -> None:
    by_id = {s.span_id: s for s in spans}
    for span in spans:
        if span.parent_span_id is None:
            continue
        parent = by_id.get(span.parent_span_id)
        if parent is None:
            raise TraceCorrelationError(
                f"span {span.span_id} ({span.name}) references unknown parent "
                f"{span.parent_span_id}; trace {span.trace_id} is unjoinable"
            )
        if parent.trace_id != span.trace_id:
            raise TraceCorrelationError(
                f"span {span.span_id} parent {parent.span_id} crosses trace_id "
                f"{span.trace_id}->{parent.trace_id}; re-parenting at a task "
                f"boundary is not permitted"
            )
        # A cross-agent parent edge must be mediated by an explicit task-received fork.
        if parent.agent_id != span.agent_id:
            if parent.name != "a2a.task.send":
                raise TraceCorrelationError(
                    f"span {span.span_id} in agent {span.agent_id} parents to "
                    f"{parent.name} in agent {parent.agent_id} without an "
                    f"a2a.task.send fork; causal nesting across agents is invalid"
                )
            if span.name != "a2a.task.received":
                raise TraceCorrelationError(
                    f"first span of agent {span.agent_id} under a2a.task.send "
                    f"must be 'a2a.task.received', got '{span.name}'; the "
                    f"receiving framework minted a local root instead of forking"
                )
        # Retries must be linked, not silently re-parented under one unit.
        if span.name.endswith(".retry") and not any(
            l.get("type") == "retry_of" for l in span.links
        ):
            raise TraceCorrelationError(
                f"retry span {span.span_id} ({span.name}) lacks a retry_of link; "
                f"error-compounding path is unreconstructable"
            )
