# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-sse-replay-corruption-when-mcp-http-native-streams-resume-under-backpressure.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-sse-replay-corruption-when-mcp-http-native-streams-resume-under-backpressure.warrant.json
# Markdown SHA-256:   c42af42b0eba853f3698c0dbda83760a49ef536f0a2d4c86800fcbcc6a8b6178
# Code AST SHA-256:   dd3595e185e877b25083b2c34ec1a02a9ab77cdf2565b47f1b750e87abfdf30f
# Verified Classes:   ResumptionInvariantError, OutboundBuffer
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class ResumptionInvariantError(RuntimeError):
    """Raised when an SSE resume request cannot be honored without violating exactly-once, in-order delivery."""
    pass


@dataclass
class OutboundBuffer:
    window_start: int
    last_emitted: int
    frames: dict = field(default_factory=dict)  # id -> payload

    def retain(self, frame_id: int, payload: dict, capacity: int) -> None:
        # Invariant: never advance last_emitted past a frame we cannot retain.
        if len(self.frames) >= capacity:
            raise ResumptionInvariantError(
                f"buffer at capacity {capacity}; refusing to emit frame {frame_id} "
                f"without retention (would create a replay gap)"
            )
        if frame_id != self.last_emitted + 1:
            raise ResumptionInvariantError(
                f"non-monotonic emission: got {frame_id}, expected {self.last_emitted + 1}"
            )
        self.frames[frame_id] = payload
        self.last_emitted = frame_id

    def resume(self, requested_id: int) -> list:
        # Invariant: exact replay or hard refusal. No clamping, no silent drop.
        if requested_id < self.window_start:
            raise ResumptionInvariantError(
                f"Last-Event-ID {requested_id} precedes retained window "
                f"start {self.window_start}; session must re-initialize"
            )
        if requested_id > self.last_emitted:
            raise ResumptionInvariantError(
                f"Last-Event-ID {requested_id} exceeds last emitted {self.last_emitted}; "
                f"client cursor is not a valid consumption proof"
            )
        return [self.frames[i] for i in range(requested_id + 1, self.last_emitted + 1)
                if i in self.frames]


def handle_resume(buf: OutboundBuffer, requested_id: Optional[int]) -> list:
    if requested_id is None:
        # Fresh stream: client has no cursor, must not receive replay.
        return []
    try:
        return buf.resume(requested_id)
    except ResumptionInvariantError:
        # Convert silent corruption into an explicit session boundary.
        raise ResumptionInvariantError(
            "resumption_unavailable: client must re-initialize and re-sync tools/list"
        )
