# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-peer-s-trust-anchor-when-a-federated-registry-re-peers-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-peer-s-trust-anchor-when-a-federated-registry-re-peers-mid-handoff.warrant.json
# Markdown SHA-256:   95954cf0c74b76a450210af097c7732d9bdee5d424cc2d1021f108059b8af66a
# Code AST SHA-256:   9167f9ab5405641c3e1a4a4a96d024b612faba855dc60d64c5b5f7b15e1209f7
# Verified Classes:   TrustEpochStraddleError, Anchor, Registry, Handoff
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class TrustEpochStraddleError(RuntimeError):
    """Raised when a handoff's commit lands in a different trust epoch than its initiation."""
    pass


@dataclass
class Anchor:
    key_id: str
    epoch: int
    signature_valid: bool = True  # cryptographic validity, independent of epoch currency


@dataclass
class Registry:
    """Authoritative federation registry; a fresh query returns the CURRENT epoch."""
    _current: dict = field(default_factory=dict)

    def set_anchor(self, peer: str, key_id: str, epoch: int) -> None:
        self._current[peer] = Anchor(key_id=key_id, epoch=epoch)

    def resolve(self, peer: str) -> Anchor:
        if peer not in self._current:
            raise TrustEpochStraddleError(f"peer {peer} not resolvable in registry")
        return self._current[peer]


@dataclass
class Handoff:
    peer: str
    initiated_epoch: int
    committed_epoch: int | None = None


def begin_handoff(registry: Registry, peer: str) -> Handoff:
    anchor = registry.resolve(peer)
    return Handoff(peer=peer, initiated_epoch=anchor.epoch)


def commit_handoff(registry: Registry, handoff: Handoff, ttl_seconds: float, elapsed: float) -> None:
    # Re-resolve only across the decision boundary: durable commit, and TTL exceeded.
    if elapsed < ttl_seconds:
        # Fast path: still within cached-anchor TTL; but this is exactly the
        # trap if the handoff outlives the TTL. We require the caller to have
        # crossed a commit boundary, so we always re-resolve here.
        pass

    current = registry.resolve(handoff.peer)

    if not current.signature_valid:
        raise TrustEpochStraddleError(
            f"anchor {current.key_id} signature invalid at commit"
        )

    if current.epoch != handoff.initiated_epoch:
        raise TrustEpochStraddleError(
            f"trust-epoch straddle on peer {handoff.peer}: "
            f"initiated under epoch {handoff.initiated_epoch}, "
            f"registry now at epoch {current.epoch}; abort and renegotiate"
        )

    handoff.committed_epoch = current.epoch


# --- demonstration of the failure and the guardrail ---
if __name__ == "__main__":
    reg = Registry()
    reg.set_anchor("orgC", key_id="K_C", epoch=7)

    h = begin_handoff(reg, "orgC")            # epoch 7 captured
    # mid-stream, orgB re-peers and rotates the anchor to epoch 8
    reg.set_anchor("orgC", key_id="K_C", epoch=8)

    try:
        # commit boundary reached after the registry changed
        commit_handoff(reg, h, ttl_seconds=30.0, elapsed=600.0)
    except TrustEpochStraddleError as e:
        print(f"GUARDRAIL FIRED: {e}")
        # correct posture: abort, renegotiate policy under epoch 8, restart transfer
