# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-local-span-parent-pointer-survive-federation-export-but-silently-re-root-the-reconstructed-agent-graph.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-local-span-parent-pointer-survive-federation-export-but-silently-re-root-the-reconstructed-agent-graph.warrant.json
# Markdown SHA-256:   02899267c9e63632b2234542a0ee6aa8634de2b9d1d9da27268e5869e507b71e
# Code AST SHA-256:   b7099cd720c45d4ed387c43a7c472b85bd31bb47091483559219640d6e4a1dc9
# Verified Classes:   DanglingParentError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DanglingParentError(RuntimeError):
    """Raised when a span claims a parent that is absent from the merged set
    and carries no federation-boundary marker. Re-rooting such a span would
    produce a structurally valid but causally false agent graph."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    name: str
    instance: str
    attributes: dict = field(default_factory=dict)


def reconstruct_agent_graph(spans: list[Span]) -> dict[str, list[str]]:
    """Build parent->children adjacency for the merged federation span set.

    Invariant: a span with a non-empty parent_span_id MUST resolve within the
    merged set, OR carry gen_ai.agent.federation_boundary=true. Otherwise it is
    a dangling-parent orphan and reconstruction must abort rather than re-root.
    """
    by_id = {s.span_id: s for s in spans}
    children: dict[str, list[str]] = {}
    roots: list[str] = []

    for s in spans:
        if not s.parent_span_id:
            roots.append(s.span_id)
            continue

        parent = by_id.get(s.parent_span_id)
        if parent is None:
            is_boundary = s.attributes.get("gen_ai.agent.federation_boundary") is True
            from_instance = s.attributes.get("gen_ai.agent.handoff.from_instance")
            if not is_boundary:
                raise DanglingParentError(
                    f"span {s.span_id!r} ({s.name}) on instance {s.instance!r} "
                    f"claims parent {s.parent_span_id!r} absent from merged set; "
                    f"no federation_boundary marker, from_instance={from_instance!r}. "
                    f"Refusing to re-root: this would fabricate a causal root."
                )
            # Explicit boundary root: causality truncated, not begun.
            roots.append(s.span_id)
            continue

        # Cross-instance edge sanity: if a handoff attribute names a source
        # instance, the resolved parent must belong to that instance.
        declared_from = s.attributes.get("gen_ai.agent.handoff.from_instance")
        if declared_from is not None and parent.instance != declared_from:
            raise DanglingParentError(
                f"span {s.span_id!r} declares handoff from {declared_from!r} "
                f"but resolved parent {parent.span_id!r} lives on "
                f"{parent.instance!r}; federation edge is inconsistent."
            )

        children.setdefault(s.parent_span_id, []).append(s.span_id)

    return {"roots": roots, "children": children}


def merge_federation(batches: list[list[Span]]) -> dict[str, list[str]]:
    merged: list[Span] = [s for batch in batches for s in batch]
    return reconstruct_agent_graph(merged)
