# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-anchor-trace-correlation-when-federated-agents-cross-organizational-mcp-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-anchor-trace-correlation-when-federated-agents-cross-organizational-mcp-boundaries.warrant.json
# Markdown SHA-256:   a6eeef0021bcb77e8c1eb35c6b17ebea9653e6494b60839579edb14f4c23833c
# Code AST SHA-256:   69e582259192c083a9f8bd3fe8bd60376f850a2ab77c2d1037eda6c212ebf7ae
# Verified Classes:   TraceCorrelationLost, FederatedCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import uuid
from dataclasses import dataclass, field


class TraceCorrelationLost(RuntimeError):
    """Raised when a federated call crosses a trust boundary without a surviving correlation anchor."""


@dataclass
class FederatedCall:
    peer_org: str
    peer_re_roots_traces: bool
    correlation_id: str = field(default_factory=lambda: str(uuid.uuid4()))
    idempotency_key: str = ""


def dispatch_federated_call(peer_org: str, peer_re_roots_traces: bool, echo_observed: bool) -> FederatedCall:
    call = FederatedCall(peer_org=peer_org, peer_re_roots_traces=peer_re_roots_traces)
    # Idempotency must derive from the origin-minted anchor, never from trace_id.
    call.idempotency_key = f"corr:{call.correlation_id}"

    if peer_re_roots_traces and not echo_observed:
        # The peer re-rooted the trace and did not echo our anchor: the logical
        # task now has no shared key across the boundary. Retrying here would
        # duplicate remote side effects, so we must fail closed.
        raise TraceCorrelationLost(
            f"peer {peer_org} re-rooted trace context and failed to echo "
            f"correlation_id={call.correlation_id}; cross-org reconciliation "
            f"and idempotent retry are undefined"
        )
    return call


# Correct path: peer echoes the anchor, so retries collapse to one execution.
ok = dispatch_federated_call("org-b", peer_re_roots_traces=True, echo_observed=True)
assert ok.idempotency_key.startswith("corr:")

# Failure path: peer re-roots and drops the anchor.
dispatch_federated_call("org-c", peer_re_roots_traces=True, echo_observed=False)
