# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-causal-trace-stitching-when-an-mcp-tool-call-and-an-a2a-handoff-share-a-span-but-diverge-in-parentage.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-causal-trace-stitching-when-an-mcp-tool-call-and-an-a2a-handoff-share-a-span-but-diverge-in-parentage.warrant.json
# Markdown SHA-256:   d4ea6198489a386b7e47097216e370b020a5163c63d42e89a7a8000eb6e7a5ed
# Code AST SHA-256:   51a1ae4ab6256c68d1dc14433f381fe6878a5c496797fcbd034ccff1a67c0059
# Verified Classes:   CausalStitchError, SpanRef, ConsumingSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CausalStitchError(RuntimeError):
    """Raised when a consuming span cannot name its cross-domain producer."""
    pass


@dataclass(frozen=True)
class SpanRef:
    trace_id: str
    span_id: str


@dataclass
class ConsumingSpan:
    name: str
    parent: Optional[SpanRef]
    input_origin_domain: str        # e.g. "self", "mcp:retrieval", "a2a:agent-auditor"
    caused_by: Optional[SpanRef]    # producer identity, required across domains


def emit_consuming_span(span: ConsumingSpan, local_domain: str) -> SpanRef:
    """
    Enforce the causal-stitch invariant: any span whose input crossed a
    trace-domain boundary MUST carry an explicit caused_by edge to the
    producing span. Re-rooting without this edge is a silent mis-attribution.
    """
    crosses_boundary = span.input_origin_domain != local_domain

    if crosses_boundary and span.caused_by is None:
        raise CausalStitchError(
            f"span {span.name!r} consumes input from foreign domain "
            f"{span.input_origin_domain!r} but has no caused_by edge; "
            f"parent={span.parent} would mis-attribute the producer to the "
            f"local planner. Refusing to emit a causally-wrong span."
        )

    if crosses_boundary and span.caused_by is not None:
        # caused_by must point into a different trace than the local parent,
        # otherwise it is a redundant (and suspicious) self-reference.
        if span.parent is not None and span.caused_by.trace_id == span.parent.trace_id:
            raise CausalStitchError(
                f"span {span.name!r} declares a cross-domain caused_by that "
                f"shares trace_id {span.caused_by.trace_id} with its local "
                f"parent; re-rooting at the boundary was not actually recorded."
            )

    return SpanRef(trace_id=span.parent.trace_id if span.parent else "local",
                   span_id=span.name)


def stitch(trace: list[ConsumingSpan], local_domain: str) -> list[tuple[str, str]]:
    """Reconstruct causal edges; caused_by is an edge, not a hint."""
    edges: list[tuple[str, str]] = []
    for s in trace:
        if s.caused_by is not None:
            edges.append((s.caused_by.span_id, s.name))
        elif s.parent is not None:
            edges.append((s.parent.span_id, s.name))
        else:
            raise CausalStitchError(
                f"span {s.name!r} has neither parent nor caused_by; "
                f"causal chain is broken at this node."
            )
    return edges
