# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-drop-causal-parent-spans-when-a-semantic-convention-conformance-test-stitches-multi-agent-traces-across-an-mcp-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-drop-causal-parent-spans-when-a-semantic-convention-conformance-test-stitches-multi-agent-traces-across-an-mcp-handoff.warrant.json
# Markdown SHA-256:   b39e63a26badd08a461d24d7867a20f5ba6e3af7134cbfc252961250ae4f08e6
# Code AST SHA-256:   3fc55bbafd4cb5050bd417da548ad2aa27ff26ce35255d8e253bc5ecc55c8c1c
# Verified Classes:   CausalStitchViolation, SpanRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class CausalStitchViolation(RuntimeError):
    """Raised when a reconstructed span's parent provenance contradicts its declared upstream agent."""


@dataclass(frozen=True)
class SpanRecord:
    span_id: str
    parent_span_id: str | None
    agent_id: str
    upstream_agent_id: str | None
    conversation_id: str
    is_synthetic_root: bool = False


def assert_causal_stitch(spans: list[SpanRecord]) -> None:
    """Validate that every reconstructed parent edge preserves agent provenance.

    Invariant: for any span S with a non-null upstream_agent_id, the span whose
    span_id == S.parent_span_id must exist, must not be a synthetic root, and
    must have agent_id == S.upstream_agent_id. Topology alone is insufficient.
    """
    by_id = {s.span_id: s for s in spans}

    for span in spans:
        if span.upstream_agent_id is None:
            continue  # root or intra-agent span; no cross-agent edge claimed

        parent = by_id.get(span.parent_span_id) if span.parent_span_id else None

        if parent is None:
            raise CausalStitchViolation(
                f"span {span.span_id} (agent={span.agent_id}) claims upstream "
                f"agent={span.upstream_agent_id} but parent {span.parent_span_id} "
                f"is unresolved in conversation {span.conversation_id}; "
                f"refusing to fabricate a synthetic root for a provenance-bearing span"
            )

        if parent.is_synthetic_root:
            raise CausalStitchViolation(
                f"span {span.span_id} (agent={span.agent_id}) was re-parented to a "
                f"synthetic root {parent.span_id}; causal edge from "
                f"{span.upstream_agent_id} lost. Topology is connected but provenance "
                f"is broken — conformance must fail, not pass."
            )

        if parent.agent_id != span.upstream_agent_id:
            raise CausalStitchViolation(
                f"span {span.span_id} declares upstream_agent_id="
                f"{span.upstream_agent_id} but resolved parent {parent.span_id} "
                f"was emitted by agent={parent.agent_id}; attribution mismatch"
            )
