# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-span-linkage-when-a-federated-peer-rewrites-its-trace-context-during-a-cross-mesh-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-span-linkage-when-a-federated-peer-rewrites-its-trace-context-during-a-cross-mesh-handoff.warrant.json
# Markdown SHA-256:   92ce350bd6e36175af91e5ea273a964b60e7edaf6f482f7a61e64bd3b6442c51
# Code AST SHA-256:   33cd73048098054853389267a7dd57a26b54fc934d933644ac9dcb1c907c9135
# Verified Classes:   CausalLinkageError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import re

_TRACEPARENT_RE = re.compile(r"^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$")
_SANCTIONED_LINK_KEYS = ("parentSpanId", "links", "tracestate.continued-from")


class CausalLinkageError(RuntimeError):
    """Raised when a federated handoff severs causal linkage silently."""


def resolve_causal_predecessor(span: dict) -> str:
    """
    Return the causal predecessor span ID for a received span, or raise.

    Canonical join order: parentSpanId -> links[] -> tracestate.continued-from.
    Arbitrary attributes (e.g. 'inbound.traceparent') are deliberately ignored
    so that a peer cannot manufacture a second, competing join key.
    """
    if span.get("parentSpanId"):
        return span["parentSpanId"]

    for link in span.get("links", []):
        if link.get("linkedSpanId"):
            return link["linkedSpanId"]

    continued = span.get("tracestate", {}).get("continued-from")
    if continued:
        m = _TRACEPARENT_RE.match(continued)
        if not m:
            raise CausalLinkageError(
                f"malformed continued-from in tracestate: {continued!r}"
            )
        return m.group(2)

    # Detect the dangerous middle ground: re-rooted, pointer stashed in a
    # non-sanctioned attribute. This is the exact condition that produces
    # divergent auditor reconstructions.
    stray = [k for k in span if k not in _SANCTIONED_LINK_KEYS
             and ("traceparent" in k or "trace_id" in k)]
    if stray:
        raise CausalLinkageError(
            "span re-rooted with foreign context in non-sanctioned field(s) "
            f"{stray}; causal join is ambiguous across auditors. "
            "Peer must emit links[] or tracestate.continued-from."
        )

    raise CausalLinkageError(
        f"span {span.get('spanId')} has no resolvable causal predecessor; "
        "handoff severed causality without a sanctioned link."
    )


def ingest_federated_span(span: dict) -> str:
    """Mesh ingress gate: reject silent re-rooting before it enters the store."""
    pred = resolve_causal_predecessor(span)
    if pred == span.get("spanId"):
        raise CausalLinkageError("self-referential causal edge detected")
    return pred
