# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-handle-mcp-streamable-sse-resumption-when-the-replay-window-has-been-evicted-but-the-client-presents-a-stale-last-event-id.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-handle-mcp-streamable-sse-resumption-when-the-replay-window-has-been-evicted-but-the-client-presents-a-stale-last-event-id.warrant.json
# Markdown SHA-256:   13ac779dec7ddf3549608014f56526596117559398a4fdc26a8f748263565ffe
# Code AST SHA-256:   aad9b5240deb32718c52140a8bb8c1d87892b4e0a9418ab8a1ca60f000e487ed
# Verified Classes:   ResumptionGapError, ReplayBuffer, StreamFold
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ResumptionGapError(RuntimeError):
    """Raised when an SSE resumption cannot be satisfied contiguously.

    Either the server evicted events the client needs (cursor < buffer head),
    or the client observed an id discontinuity in the incoming stream.
    In both cases the session state is unrecoverable and must be re-initialized.
    """


@dataclass
class ReplayBuffer:
    head_id: int                      # oldest retained event id
    tail_id: int                      # newest emitted event id
    events: dict = field(default_factory=dict)  # id -> payload

    def can_resume(self, cursor: int) -> bool:
        return cursor >= self.head_id


def handle_resumption_request(buf: ReplayBuffer, last_event_id: Optional[int]) -> list:
    """Server side: decide replay vs. loud rejection. Never partially resume."""
    if last_event_id is None:
        return []  # fresh stream, no continuity claim
    if not buf.can_resume(last_event_id):
        # The client's cursor is older than what we retained. We cannot
        # reconstruct its state. Fail loudly; do not open a live stream
        # at head as if resumption succeeded.
        raise ResumptionGapError(
            f"cursor {last_event_id} evicted; buffer head is {buf.head_id}. "
            f"Client must re-initialize; do not resume."
        )
    return [buf.events[i] for i in range(last_event_id + 1, buf.tail_id + 1)
            if i in buf.events]


class StreamFold:
    """Client side: fold the event stream, asserting contiguity."""

    def __init__(self, start_id: Optional[int] = None):
        self.last_id = start_id

    def apply(self, event_id: int, payload: dict) -> None:
        if self.last_id is not None and event_id != self.last_id + 1:
            raise ResumptionGapError(
                f"expected id {self.last_id + 1}, got {event_id}; "
                f"events in between were lost. Re-initialize session."
            )
        self.last_id = event_id
        # ... fold payload into agent state ...


def resync_session(client: StreamFold, server: ReplayBuffer,
                   last_event_id: Optional[int]) -> list:
    """End-to-end: server decides, client enforces. Both guards are required."""
    try:
        replayed = handle_resumption_request(server, last_event_id)
    except ResumptionGapError:
        # Server rejected: force clean restart, replay intent not transcript.
        client.last_id = None
        raise
    for ev in replayed:
        client.apply(ev["id"], ev["payload"])  # client re-checks contiguity
    return replayed
