# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-replayed-a2a-message-as-a-session-binding-failure-rather-than-an-idempotency-hit.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-replayed-a2a-message-as-a-session-binding-failure-rather-than-an-idempotency-hit.warrant.json
# Markdown SHA-256:   eace8e20a6f9c2f8ca63c89a7d6091d42b9c6f8bc03a42e0b7ce68e723c2a1cf
# Code AST SHA-256:   d0770c7394e613599f46f84849dcae54a6b7b8757024a9ed4368c6284b5b426e
# Verified Classes:   ReplayBindingError, SessionBinding
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ReplayBindingError(RuntimeError):
    """Raised when a frame decrypts cleanly but its sequence number is stale
    relative to the live session epoch — evidence of replay, not idempotency."""
    pass


class SessionBinding:
    def __init__(self, epoch: int, window: int, dedup_capacity: int):
        assert dedup_capacity >= window, "dedup cache must cover replay window"
        self.epoch = epoch
        self.window = window
        self.last_seen = 0
        self.dedup = {}  # (epoch, seq) -> result
        self.dedup_capacity = dedup_capacity

    def receive(self, frame_epoch: int, seq: int, decrypt_fn, execute_fn):
        if frame_epoch != self.epoch:
            # Frame belongs to a prior session; key may be rotated.
            raise ReplayBindingError(
                f"epoch mismatch: frame={frame_epoch} live={self.epoch}"
            )

        if seq <= self.last_seen:
            key = (self.epoch, seq)
            if key in self.dedup:
                return self.dedup[key]  # legitimate retry within epoch
            # Stale sequence, no dedup entry: decrypting proves the sender
            # held K_s at capture time, NOT that it holds it now.
            self._teardown()
            raise ReplayBindingError(
                f"stale seq={seq} <= last_seen={self.last_seen} "
                f"with no dedup entry; treating clean decrypt as replay"
            )

        if seq > self.last_seen + self.window:
            raise ReplayBindingError(
                f"seq={seq} outside window [{self.last_seen+1}, "
                f"{self.last_seen+self.window}]"
            )

        result = execute_fn(decrypt_fn())
        self.last_seen = seq
        self.dedup[(self.epoch, seq)] = result
        if len(self.dedup) > self.dedup_capacity:
            oldest = min(self.dedup)
            del self.dedup[oldest]
        return result

    def _teardown(self):
        self.epoch += 1
        self.last_seen = 0
        self.dedup.clear()
