# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-cannot-reconcile-its-mcp-transport-trace-with-its-a2a-task-span-and-its-aaif-identity-assertion-inside-one-causal-graph.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-cannot-reconcile-its-mcp-transport-trace-with-its-a2a-task-span-and-its-aaif-identity-assertion-inside-one-causal-graph.warrant.json
# Markdown SHA-256:   50909291b35d35172c9b57f91f4cb805ac73cbe45124638cfc6924b26670be36
# Code AST SHA-256:   35c7f956372698e1d333a5a1c5fe033e163ed06ecfbfeb7d624ed0a87175d992
# Verified Classes:   CausalCorrelationError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CausalCorrelationError(RuntimeError):
    """Raised when a span's asserted parent cannot be resolved in the causal graph."""


@dataclass
class Span:
    layer: str            # "mcp" | "a2a" | "aaif"
    span_id: str
    parent_id: Optional[str]
    trace_id: str
    certainty: str        # "asserted" | "inferred"


def build_causal_graph(spans: list[Span]) -> dict[str, list[str]]:
    """Join spans into a parent->children map, failing closed on unresolved parents."""
    by_id = {s.span_id: s for s in spans}
    graph: dict[str, list[str]] = {}

    for span in spans:
        if span.parent_id is None:
            # Root span: permitted only if it is the originating A2A task.
            if span.layer != "a2a":
                raise CausalCorrelationError(
                    f"non-A2A span {span.span_id} ({span.layer}) has no parent; "
                    "MCP and AAIF spans must adopt a propagated parent"
                )
            graph.setdefault(span.span_id, [])
            continue

        parent = by_id.get(span.parent_id)
        if parent is None:
            # Parent was dropped or never propagated across a hop.
            raise CausalCorrelationError(
                f"span {span.span_id} ({span.layer}) asserts parent "
                f"{span.parent_id} which is absent from the graph; "
                "quarantine to orphaned_spans rather than infer a join"
            )

        if span.certainty == "inferred":
            # Inferred edges may annotate but must not be promoted to asserted.
            if span.layer in ("mcp", "aaif"):
                raise CausalCorrelationError(
                    f"span {span.span_id} ({span.layer}) reached the graph via "
                    "heuristic join; attribution queries must not traverse it"
                )

        graph.setdefault(span.parent_id, []).append(span.span_id)

    return graph


def assert_attribution_safe(graph: dict[str, list[str]], spans: list[Span]) -> None:
    """Reject graphs where any asserted edge is actually inferred, before audit use."""
    by_id = {s.span_id: s for s in spans}
    for parent, children in graph.items():
        for child in children:
            if by_id[child].certainty != "asserted":
                raise CausalCorrelationError(
                    f"attribution query over edge {parent}->{child} rejected: "
                    f"certainty={by_id[child].certainty}"
                )
