# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-sse-stream-resurrection-from-corrupting-resumable-mcp-sessions-across-transport-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-sse-stream-resurrection-from-corrupting-resumable-mcp-sessions-across-transport-reconnect.warrant.json
# Markdown SHA-256:   651d914fd70d8fc2a176a1d4653c3ad2e7c5bd73d286d8e88164f6bb377b5957
# Code AST SHA-256:   6d170b5cb301908c78163c74724674d516016d69e8487bfe75d69a187edf0a2c
# Verified Classes:   StaleEventReplayError, RequestEntry, EventFrame, Session
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class StaleEventReplayError(RuntimeError):
    """Raised when a replayed SSE frame belongs to a request generation that is no longer live."""


@dataclass
class RequestEntry:
    request_id: str
    epoch: int
    registered_at: float
    ttl_s: float

    def alive(self, now: float) -> bool:
        return (now - self.registered_at) < self.ttl_s


@dataclass
class EventFrame:
    event_id: int
    request_id: str
    epoch: int
    payload: dict[str, Any]


@dataclass
class Session:
    session_id: str
    registry: dict[str, RequestEntry] = field(default_factory=dict)
    event_buffer: list[EventFrame] = field(default_factory=list)
    epoch_counter: int = 0
    terminal_seen: set[tuple[str, int]] = field(default_factory=set)

    def register(self, request_id: str, ttl_s: float) -> RequestEntry:
        self.epoch_counter += 1
        entry = RequestEntry(request_id, self.epoch_counter, time.monotonic(), ttl_s)
        self.registry[request_id] = entry
        return entry

    def emit(self, request_id: str, epoch: int, payload: dict[str, Any]) -> None:
        """Guarded emit: refuse to append frames for deregistered or superseded requests."""
        entry = self.registry.get(request_id)
        now = time.monotonic()
        if entry is None or not entry.alive(now) or entry.epoch != epoch:
            # Late completion from a tool handler whose request died: drop, do not buffer.
            return
        self.event_buffer.append(EventFrame(len(self.event_buffer) + 1, request_id, epoch, payload))

    def resume(self, last_event_id: int) -> list[EventFrame]:
        """Return replayable frames, rejecting stale-epoch frames the client must not apply."""
        out: list[EventFrame] = []
        for frame in self.event_buffer:
            if frame.event_id <= last_event_id:
                continue
            entry = self.registry.get(frame.request_id)
            if entry is None or entry.epoch != frame.epoch:
                # Stale generation: surface to caller, never hand to the reasoning layer.
                raise StaleEventReplayError(
                    f"session={self.session_id} event={frame.event_id} "
                    f"request={frame.request_id} epoch={frame.epoch} has no live registry entry"
                )
            key = (frame.request_id, frame.epoch)
            if key in self.terminal_seen:
                continue
            if frame.payload.get("type") in ("result", "error"):
                self.terminal_seen.add(key)
            out.append(frame)
        return out


def apply_resumed_frames(session: Session, last_event_id: int, slot_id: str) -> list[dict[str, Any]]:
    """Client-side application path; enforces epoch match against the open slot."""
    frames = session.resume(last_event_id)
    applied: list[dict[str, Any]] = []
    for frame in frames:
        if frame.request_id != slot_id:
            continue
        entry = session.registry.get(frame.request_id)
        if entry is None or entry.epoch != frame.epoch:
            raise StaleEventReplayError(
                f"refusing to apply stale frame {frame.event_id} to slot {slot_id}"
            )
        applied.append(frame.payload)
    return applied
