# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-a-span-when-its-traceparent-crosses-a-federated-collector-boundary-with-a-rewritten-trace-id.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-a-span-when-its-traceparent-crosses-a-federated-collector-boundary-with-a-rewritten-trace-id.warrant.json
# Markdown SHA-256:   0821eb45df68239bdc0455fe424378270c2193699ead07ee8e4dd5d671c9cced
# Code AST SHA-256:   e4879d1b2fcd152822f5cb6e2b67a36413eb68dd48d8ddf34c3c2fb6ccdf5a4b
# Verified Classes:   TraceCorrelationSplit
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TraceCorrelationSplit(RuntimeError):
    """Raised when a federated collector boundary has re-parented a span
    into a different trace_id than its causal parent, producing a
    silently-consistent but false causal graph."""
    pass


def verify_span_lineage(span: dict, parent_span: dict, origin_trace_id: str) -> None:
    """
    Guard invoked at every agent boundary before a span is accepted into
    the local causal record. Enforces the federation invariant:
    trace_id is immutable identity, not a routing hint.
    """
    current_trace = span.get("trace_id")
    parent_trace = parent_span.get("trace_id")
    parent_id = span.get("parent_span_id")
    parent_span_id = parent_span.get("span_id")

    # Structural check: parent linkage must be internally coherent.
    if parent_id is not None and parent_id != parent_span_id:
        raise TraceCorrelationSplit(
            f"span {span.get('span_id')} declares parent {parent_id} "
            f"but causal parent span is {parent_span_id}"
        )

    # Federation check: origin trace id must survive every collector hop.
    if current_trace != origin_trace_id:
        raise TraceCorrelationSplit(
            f"span {span.get('span_id')} arrived with trace_id={current_trace} "
            f"but chain origin is {origin_trace_id}: a federated collector "
            f"rewrote the trace identity, splitting the causal graph"
        )

    # Cross-trace parent check: the silent-split signature.
    if parent_trace is not None and parent_trace != current_trace:
        raise TraceCorrelationSplit(
            f"span {span.get('span_id')} (trace {current_trace}) has parent "
            f"{parent_span_id} in trace {parent_trace}: re-parenting detected, "
            f"refusing to attest lineage"
        )
