# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-across-a-serverless-cold-start-and-the-resumption-cursor-outlives-the-session-that-minted-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-across-a-serverless-cold-start-and-the-resumption-cursor-outlives-the-session-that-minted-it.warrant.json
# Markdown SHA-256:   44d55e686ebdaf48ca9a630cd1bb0405d1dc88570f3c42549462f2ffa92efead
# Code AST SHA-256:   1814c102008c351875528b1c4475865d758cf616525f490eae3e0dbc922cb94d
# Verified Classes:   ResumptionContractViolation, ReconnectRequest, SessionRecord, EventStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ResumptionContractViolation(RuntimeError):
    """Raised when a reconnect carrying Last-Event-ID cannot be honored.

    The server must NOT return 200 here: a 200 on a cursor-bearing reconnect
    is a promise that the cursor was replayed. Violating that promise is the
    silent-corruption failure this record documents.
    """
    pass


@dataclass
class ReconnectRequest:
    session_id: Optional[str]
    last_event_id: Optional[int]


@dataclass
class SessionRecord:
    session_id: str
    alive: bool


@dataclass
class EventStore:
    # durable, keyed by (session_id, event_id); survives instance reclamation
    events: dict
    max_event_id: dict  # session_id -> highest durable event id

    def has_cursor(self, session_id: str, cursor: int) -> bool:
        return self.events.get((session_id, cursor)) is not None

    def is_closed(self, session_id: str) -> bool:
        # a stream is closed once its terminal result event is durable
        return self.events.get((session_id, "closed")) is True


def handle_reconnect(
    req: ReconnectRequest,
    sessions: dict,
    store: EventStore,
) -> str:
    """Returns 'replay' or 'fresh'. Raises on the dangerous quadrant."""
    if req.session_id is None:
        return "fresh"

    sess: Optional[SessionRecord] = sessions.get(req.session_id)
    if sess is None or not sess.alive:
        # unambiguous: client must re-initialize
        raise ResumptionContractViolation(
            f"session {req.session_id} unknown; re-initialize required"
        )

    if req.last_event_id is None:
        return "fresh"

    # Session is valid. Now the cursor must independently prove itself.
    if not store.has_cursor(req.session_id, req.last_event_id):
        if store.is_closed(req.session_id):
            # session alive, cursor gone, stream already terminated:
            # returning 200 here would silently truncate the agent's history.
            raise ResumptionContractViolation(
                f"cursor {req.last_event_id} for session {req.session_id} "
                f"is not durable; refusing to open a fresh stream under a "
                f"valid session (silent-truncation hazard)"
            )
        raise ResumptionContractViolation(
            f"cursor {req.last_event_id} unknown for live session "
            f"{req.session_id}; cannot honor Last-Event-ID"
        )

    return "replay"
