# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-an-mcp-gateway-pass-semantic-convention-compliance-on-every-span-while-the-end-to-end-trace-still-loses-the-causal-link-betwee.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-an-mcp-gateway-pass-semantic-convention-compliance-on-every-span-while-the-end-to-end-trace-still-loses-the-causal-link-betwee.warrant.json
# Markdown SHA-256:   54082a7422e42ed5864bde477aa285b38fd972009e2cb397636d2b2f0c816980
# Code AST SHA-256:   87ecfacc13784d4cfc06114eeee9cb0c43a46340ad6983be677a88deeba04810
# Verified Classes:   TraceGraphConformanceError, Span
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import uuid
from dataclasses import dataclass, field
from typing import Optional


class TraceGraphConformanceError(RuntimeError):
    """Raised when per-span conformance passes but the trace graph loses causal linkage."""
    pass


@dataclass
class Span:
    span_id: str
    trace_id: str
    parent_span_id: Optional[str]
    operation: str
    tool_call_id: Optional[str] = None
    attributes_valid: bool = True


def assert_causal_linkage(spans: list[Span], expected_tool_call_id: str) -> None:
    """
    Assert the invariant: every gateway execute_tool span has a chat ancestor
    in the same trace, and tool_call_id matches across the chain.
    """
    by_id = {s.span_id: s for s in spans}

    gateway_spans = [
        s for s in spans
        if s.operation == "execute_tool" and s.parent_span_id is None
    ]
    if gateway_spans:
        bad = gateway_spans[0]
        raise TraceGraphConformanceError(
            f"gateway execute_tool span {bad.span_id} in trace {bad.trace_id} "
            f"is a root (parent_span_id=None): context propagation was dropped "
            f"at the gateway boundary; causal edge to agent chat span is lost"
        )

    for s in spans:
        if s.operation != "execute_tool":
            continue
        if s.tool_call_id != expected_tool_call_id:
            raise TraceGraphConformanceError(
                f"span {s.span_id} tool_call_id={s.tool_call_id!r} != "
                f"expected {expected_tool_call_id!r}: chain is not joinable"
            )
        cursor = s
        found_chat = False
        seen = set()
        while cursor.parent_span_id is not None:
            if cursor.span_id in seen:
                raise TraceGraphConformanceError(
                    f"cycle detected walking ancestors of {s.span_id}"
                )
            seen.add(cursor.span_id)
            parent = by_id.get(cursor.parent_span_id)
            if parent is None:
                raise TraceGraphConformanceError(
                    f"span {cursor.span_id} references missing parent "
                    f"{cursor.parent_span_id}: trace is truncated"
                )
            if parent.operation == "chat":
                found_chat = True
                break
            cursor = parent
        if not found_chat:
            raise TraceGraphConformanceError(
                f"execute_tool span {s.span_id} has no chat ancestor in trace "
                f"{s.trace_id}: replay cannot attribute tool effect to a decision"
            )


def run_compliance(spans: list[Span], expected_tool_call_id: str) -> None:
    for s in spans:
        if not s.attributes_valid:
            raise TraceGraphConformanceError(
                f"span {s.span_id} fails per-span attribute conformance"
            )
    assert_causal_linkage(spans, expected_tool_call_id)


if __name__ == "__main__":
    trace = str(uuid.uuid4())
    chat = Span("a1", trace, None, "chat")
    client_tool = Span("a2", trace, "a1", "execute_tool", tool_call_id="tc-9")
    # Gateway re-rooted: parent_span_id is None instead of "a2"
    gateway_tool = Span("b1", str(uuid.uuid4()), None, "execute_tool", tool_call_id="tc-9")
    run_compliance([chat, client_tool, gateway_tool], "tc-9")
