# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-peer-s-policy-exchange-handshake-after-trust-anchor-rotation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-peer-s-policy-exchange-handshake-after-trust-anchor-rotation.warrant.json
# Markdown SHA-256:   4686600e6a752c1bb96afd4cef92153f671b49348e252792870982b002d091b4
# Code AST SHA-256:   0ed445ff9bd24bf453a20a12bfac61bed06999c040e75380c37fb50ef36f6eba
# Verified Classes:   AnchorDriftError, SessionPolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class AnchorDriftError(RuntimeError):
    """Raised when a policy update's anchor differs from the session's pinned anchor."""
    pass


class SessionPolicy:
    def __init__(self, session_id: str, pinned_anchor_id: str, policy_bundle: dict):
        self.session_id = session_id
        self.pinned_anchor_id = pinned_anchor_id
        self.policy_bundle = dict(policy_bundle)


def admit_policy_update(
    session: SessionPolicy,
    update_anchor_id: str,
    update_bundle: dict,
    chain_reaches_pinned_root: bool,
) -> SessionPolicy:
    # Chain-reachability is necessary but not sufficient: a rotated anchor
    # cross-signed by the pinned root will pass this check and must still
    # be rejected mid-session, because the session is bound to a snapshot.
    if not chain_reaches_pinned_root:
        raise AnchorDriftError(
            f"session {session.session_id}: update anchor {update_anchor_id} "
            f"does not chain to pinned root {session.pinned_anchor_id}"
        )

    if update_anchor_id != session.pinned_anchor_id:
        # Split-anchor window: valid signature, valid chain, wrong anchor
        # for this session's policy snapshot. Force re-handshake.
        raise AnchorDriftError(
            f"session {session.session_id}: anchor rotation detected "
            f"({session.pinned_anchor_id} -> {update_anchor_id}); "
            f"policy merge refused, re-handshake required"
        )

    # Same anchor: merge is admissible under the frozen-snapshot invariant.
    merged = dict(session.policy_bundle)
    merged.update(update_bundle)
    return SessionPolicy(session.session_id, session.pinned_anchor_id, merged)
