# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-after-a-server-side-cancellation-and-the-last-event-id-cursor-lands-on-a-tombstoned-request.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-after-a-server-side-cancellation-and-the-last-event-id-cursor-lands-on-a-tombstoned-request.warrant.json
# Markdown SHA-256:   f6bd5e45f28e0b88e488bef4bac9596b261a1e2ed536a4456d7ed3d1401aebed
# Code AST SHA-256:   a1a0bed9f72064452988eea0e89b988559037703a898ab3822398bbce95a371d
# Verified Classes:   OrphanedCancellationError, RequestTombstone, SessionEventLog
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class OrphanedCancellationError(RuntimeError):
    """Raised when a cancellation is replayed to a generation that never
    dispatched the target request, and the server has no tombstone to
    convert it into a terminal request-expired event."""


@dataclass
class RequestTombstone:
    request_id: str
    dispatched_generation: int
    terminal: bool = False


@dataclass
class SessionEventLog:
    session_id: str
    generation: int = 0
    events: list = field(default_factory=list)  # (sse_id, kind, request_id)
    tombstones: Dict[str, RequestTombstone] = field(default_factory=dict)

    def new_connection(self) -> int:
        self.generation += 1
        return self.generation

    def dispatch(self, request_id: str) -> None:
        self.tombstones[request_id] = RequestTombstone(
            request_id=request_id, dispatched_generation=self.generation
        )

    def cancel(self, request_id: str) -> None:
        ts = self.tombstones.get(request_id)
        if ts is None:
            raise OrphanedCancellationError(
                f"cancel for undispatched request {request_id}"
            )
        ts.terminal = True
        self.events.append((len(self.events) + 1, "cancelled", request_id))

    def replay(self, last_event_id: int) -> list:
        """Return events safe to replay to the CURRENT generation.

        Additive events (progress) replay unconditionally. Terminal events
        (cancelled) replay only if the current generation dispatched the
        target; otherwise they are rewritten to request-expired, which is
        idempotent and does not require the client to hold request state.
        """
        out = []
        for sse_id, kind, req_id in self.events:
            if sse_id <= last_event_id:
                continue
            if kind == "cancelled":
                ts = self.tombstones.get(req_id)
                if ts is None:
                    raise OrphanedCancellationError(
                        f"tombstone missing for {req_id} during replay"
                    )
                if ts.dispatched_generation != self.generation:
                    out.append((sse_id, "request-expired", req_id))
                    continue
            out.append((sse_id, kind, req_id))
        return out


def handle_reconnect(log: SessionEventLog, last_event_id: int) -> list:
    if last_event_id > len(log.events):
        # stale cursor from a pre-restart log; force fresh stream
        log.new_connection()
        return []
    log.new_connection()
    try:
        return log.replay(last_event_id)
    except OrphanedCancellationError as exc:
        # fail closed: never emit a cancellation we cannot correlate
        raise OrphanedCancellationError(
            f"session {log.session_id} gen {log.generation}: refusing to "
            f"replay uncorrelatable terminal event: {exc}"
        ) from exc
