# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-sse-resumption-corruption-when-an-mcp-server-migrates-a-session-from-streamable-http-to-a-resumed-event-stream-mid-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-sse-resumption-corruption-when-an-mcp-server-migrates-a-session-from-streamable-http-to-a-resumed-event-stream-mid-tool-call.warrant.json
# Markdown SHA-256:   248ac6553eb1ebd8a700838ed92f72f811ceb6aaa8abbd7ad56d4fb3151b4e83
# Code AST SHA-256:   d54bd407040807d6caeaf4d6dad3663e7d3bd1d3a315e285b6ea52eebf2a8b72
# Verified Classes:   ResumptionInvariantViolation, Event, SessionBuffer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Literal


class ResumptionInvariantViolation(RuntimeError):
    """Raised when an MCP streamable-HTTP resumption would corrupt session state."""


@dataclass(frozen=True)
class Event:
    event_id: int
    jsonrpc_id: int | None
    kind: Literal["progress", "result", "error"]
    progress_token: str | None = None


@dataclass
class SessionBuffer:
    session_id: str
    events: list[Event] = field(default_factory=list)
    delivered_terminal: set[int] = field(default_factory=set)  # jsonrpc_ids already sent
    resumption_mode: Literal["buffer", "checkpoint"] = "buffer"

    def resume(self, last_event_id: int, side_effecting_tool: bool) -> list[Event]:
        if side_effecting_tool and self.resumption_mode == "buffer":
            raise ResumptionInvariantViolation(
                f"session {self.session_id}: replay-from-buffer forbidden for "
                f"side-effecting tool; executor state may have advanced past "
                f"event {last_event_id}"
            )

        tail = [e for e in self.events if e.event_id > last_event_id]

        # At-most-once terminal delivery: drop any terminal event whose
        # jsonrpc_id was already delivered on a prior connection.
        deduped: list[Event] = []
        for e in tail:
            if e.kind in ("result", "error") and e.jsonrpc_id is not None:
                if e.jsonrpc_id in self.delivered_terminal:
                    continue
                self.delivered_terminal.add(e.jsonrpc_id)
            deduped.append(e)

        # Prefix-consistency: IDs in the replayed suffix must be contiguous
        # and strictly increasing.
        for prev, cur in zip(deduped, deduped[1:]):
            if cur.event_id != prev.event_id + 1:
                raise ResumptionInvariantViolation(
                    f"session {self.session_id}: non-contiguous replay "
                    f"({prev.event_id} -> {cur.event_id}); buffer segmented "
                    f"by token or phase, not by session"
                )

        # Progress-token termination: if the last delivered event was a
        # progress event for token T, the replayed suffix must either
        # terminate T or not reference it at all.
        if tail and tail[0].kind == "progress":
            last_delivered_token = self._token_at(last_event_id)
            if last_delivered_token and tail[0].progress_token == last_delivered_token:
                # Resume mid-phase is fine; resume that skips the terminal
                # progress for T is not.
                if not any(
                    e.kind == "progress"
                    and e.progress_token == last_delivered_token
                    and e.progress_token is not None
                    for e in deduped
                ):
                    raise ResumptionInvariantViolation(
                        f"session {self.session_id}: resumed into token "
                        f"{last_delivered_token} without termination event; "
                        f"client will observe unterminated progress stream"
                    )

        return deduped

    def _token_at(self, event_id: int) -> str | None:
        for e in self.events:
            if e.event_id == event_id:
                return e.progress_token
        return None
