# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-attestation-envelope-replay-window-has-silently-widened-across-an-a2a-nonce-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-attestation-envelope-replay-window-has-silently-widened-across-an-a2a-nonce-chain.warrant.json
# Markdown SHA-256:   ca8aff46dec4cbabe038dfdb546b6121740f648bb182a312df374e793e354268
# Code AST SHA-256:   c481780166dd37588fd63f9db394402cfd45eaeed1ba98573403651ef8a00c6e
# Verified Classes:   AttestationReplayWindowError, Envelope, EpochScopedReplayCache
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, Tuple


class AttestationReplayWindowError(RuntimeError):
    """Raised when an envelope would be accepted under a replay window
    wider than the single-message invariant permits."""
    pass


@dataclass(frozen=True)
class Envelope:
    peer_id: str
    nonce: int
    key_epoch: int
    signature_valid: bool


class EpochScopedReplayCache:
    def __init__(self) -> None:
        # Key MUST be (peer_id, key_epoch). An epoch-blind key is the bug.
        self._high_water: Dict[Tuple[str, int], int] = {}
        self._current_epoch: Dict[str, int] = {}
        self._grace_epochs: Dict[str, set] = {}

    def set_epoch(self, peer_id: str, current: int, grace: set) -> None:
        self._current_epoch[peer_id] = current
        self._grace_epochs[peer_id] = set(grace)

    def accept(self, env: Envelope) -> None:
        if not env.signature_valid:
            raise AttestationReplayWindowError(
                f"attestation signature invalid for peer={env.peer_id}"
            )

        current = self._current_epoch.get(env.peer_id)
        if current is None:
            raise AttestationReplayWindowError(
                f"no epoch registered for peer={env.peer_id}; "
                f"cannot bound replay window"
            )

        is_current = env.key_epoch == current
        is_grace = env.key_epoch in self._grace_epochs.get(env.peer_id, set())

        if not (is_current or is_grace):
            raise AttestationReplayWindowError(
                f"envelope epoch={env.key_epoch} for peer={env.peer_id} "
                f"is neither current={current} nor in grace; "
                f"provenance and freshness validators disagree"
            )

        key = (env.peer_id, env.key_epoch)
        frontier = self._high_water.get(key)

        # Structural invariant: a nonce reset under a NEW epoch must not be
        # compared against a frontier recorded under a DIFFERENT epoch.
        if frontier is not None and env.nonce <= frontier:
            raise AttestationReplayWindowError(
                f"replay detected: peer={env.peer_id} epoch={env.key_epoch} "
                f"nonce={env.nonce} <= frontier={frontier}"
            )

        if is_grace and frontier is None:
            # First grace-epoch message with no recorded frontier means the
            # retired epoch was never tracked: the replay range is unbounded.
            raise AttestationReplayWindowError(
                f"grace-epoch={env.key_epoch} for peer={env.peer_id} has no "
                f"recorded high-water mark; replay window is unbounded"
            )

        self._high_water[key] = env.nonce


def handle_handoff(cache: EpochScopedReplayCache, env: Envelope) -> str:
    cache.accept(env)
    return f"accepted peer={env.peer_id} epoch={env.key_epoch} nonce={env.nonce}"
