# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-trace-roots-when-federated-observability-spans-cross-an-organizational-trust-boundary-mid-episode.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-trace-roots-when-federated-observability-spans-cross-an-organizational-trust-boundary-mid-episode.warrant.json
# Markdown SHA-256:   a482c6a58b3abf8d7b72c56739b90959f6e8bf63e875e55f2482c472e15f9147
# Code AST SHA-256:   db399c2a3af9375433c2e9d1a036f1d2ea9a2749311c3baf6dbb9decec59f893
# Verified Classes:   FederatedJoinError, FederatedJoin
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class FederatedJoinError(RuntimeError):
    """Raised when root assignment or join reconciliation violates the
    federated correlation invariant."""


@dataclass
class FederatedJoin:
    correlation_id: str
    roots: dict = field(default_factory=dict)      # root_id -> authority org
    cross_edges: list = field(default_factory=list)  # (from_root, to_root)

    def assign_root(self, root_id: str, authority: str, inbound_ref: str | None):
        # Invariant: roots must be one-per-authority for a correlation_id.
        for existing_root, existing_auth in self.roots.items():
            if existing_auth == authority and existing_root != root_id:
                raise FederatedJoinError(
                    f"correlation {self.correlation_id}: org {authority} already "
                    f"owns root {existing_root}; refusing to mint {root_id} "
                    f"(return-leg re-entry must link, not re-root)"
                )
        if inbound_ref is not None:
            self.cross_edges.append((inbound_ref, root_id))
        self.roots[root_id] = authority

    def verify(self):
        authorities = list(self.roots.values())
        if len(authorities) != len(set(authorities)):
            raise FederatedJoinError(
                f"correlation {self.correlation_id}: root count {len(authorities)} "
                f"!= distinct authorities {len(set(authorities))}"
            )
        return True


def handle_ingress(join: FederatedJoin, inbound_root: str, local_org: str,
                   inbound_authority: str):
    # Stateful test: does a local root already exist for this correlation?
    local_roots = [r for r, a in join.roots.items() if a == local_org]
    if local_roots:
        # Return leg: link to existing local root, do not mint.
        existing = local_roots[0]
        join.cross_edges.append((inbound_root, existing))
        return existing
    if inbound_authority == local_org:
        raise FederatedJoinError(
            f"inbound root {inbound_root} claims local authority {local_org} "
            f"but no local root exists for {join.correlation_id}; "
            f"authority spoofing or index loss — fail closed"
        )
    new_root = f"{local_org}-{join.correlation_id}-root"
    join.assign_root(new_root, local_org, inbound_ref=inbound_root)
    join.verify()
    return new_root
