# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trace-context-collapse-when-a-federated-agent-mesh-crosses-a-vendor-boundary-that-rewrites-span-identity.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trace-context-collapse-when-a-federated-agent-mesh-crosses-a-vendor-boundary-that-rewrites-span-identity.warrant.json
# Markdown SHA-256:   8d9c16b3aec7f9ced6d5b25691cd4e3969bbb103edcc63f24d3afa3c2a4e1f2d
# Code AST SHA-256:   0b34a457fd74e34875eede7e4f9d717adfcf4f58b061bdd60408c699064b210d
# Verified Classes:   TraceCorrelationCollapse, SpanRef, HandoffRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TraceCorrelationCollapse(RuntimeError):
    """Raised when a cross-boundary handoff severs the causal edge silently."""
    pass


@dataclass(frozen=True)
class SpanRef:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]


@dataclass(frozen=True)
class HandoffRecord:
    outbound: SpanRef          # what the delegator sent
    inbound_result: SpanRef    # what the executor claims as its root
    boundary_trusted: bool     # does this boundary preserve parentage?


def assert_correlation_intact(record: HandoffRecord) -> None:
    """
    Enforce: a returned child must resolve to the delegator's outbound span
    under the SAME trace_id, OR the boundary must be declared link-only.
    Never synthesize a parent edge to paper over a re-mint.
    """
    out, child = record.outbound, record.inbound_result

    if child.trace_id != out.trace_id:
        # Boundary re-minted identity (DAG fork). Acceptable only if declared.
        if record.boundary_trusted:
            raise TraceCorrelationCollapse(
                f"trusted boundary re-minted trace: "
                f"sent {out.trace_id}, got {child.trace_id}; causal edge lost"
            )
        # link-not-parent is the honest outcome; do NOT fabricate parentage.
        return

    # Same trace: the child's parent MUST be the span we actually sent.
    if child.parent_span_id != out.span_id:
        raise TraceCorrelationCollapse(
            f"parent mismatch in trace {out.trace_id}: "
            f"expected parent {out.span_id}, child claims {child.parent_span_id}"
        )


def reconcile_handoff(record: HandoffRecord) -> str:
    assert_correlation_intact(record)
    if record.inbound_result.trace_id != record.outbound.trace_id:
        return "linked"   # fork preserved as explicit link, not a fake parent
    return "parented"     # verified causal edge
