# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-streamable-http-sse-last-event-id-resume-as-a-new-turn-rather-than-a-continuation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-streamable-http-sse-last-event-id-resume-as-a-new-turn-rather-than-a-continuation.warrant.json
# Markdown SHA-256:   193c4c948000bdb46acc18ee0a7258912a1537a4b5ae9a68cdfc16e571b07168
# Code AST SHA-256:   43f664fe77830e52b862a020bca123e55237cd70b5e2211387cc2cd21317d236
# Verified Classes:   ResumeEpochMismatch, ResumeHandshake
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ResumeEpochMismatch(RuntimeError):
    """Raised when an SSE resume crosses a state-epoch boundary and cannot be
    safely spliced onto the in-flight reasoning trace."""


@dataclass(frozen=True)
class ResumeHandshake:
    session_id: str
    last_event_id: int
    resume_epoch: int | None   # None => server did not report an epoch
    last_seen_epoch: int


def admit_resumed_event(handshake: ResumeHandshake, pending_token: str) -> str:
    """Gate a replayed SSE event before it enters the pending-call table.

    Returns 'continuation' or 're-derivation'. Raises when the server's epoch
    is missing or advanced, because splicing would merge divergent branches.
    """
    if handshake.resume_epoch is None:
        # Fail closed: absence of proof is not proof of continuity.
        raise ResumeEpochMismatch(
            f"session {handshake.session_id}: server omitted state_epoch at "
            f"Last-Event-ID={handshake.last_event_id}; refusing to splice "
            f"pending token {pending_token!r} as a continuation"
        )

    if handshake.resume_epoch > handshake.last_seen_epoch:
        raise ResumeEpochMismatch(
            f"session {handshake.session_id}: state_epoch advanced "
            f"{handshake.last_seen_epoch} -> {handshake.resume_epoch} across "
            f"Last-Event-ID={handshake.last_event_id}; event is a "
            f"re-derivation, pending token {pending_token!r} is invalid"
        )

    if handshake.resume_epoch < handshake.last_seen_epoch:
        raise ResumeEpochMismatch(
            f"session {handshake.session_id}: state_epoch regressed "
            f"{handshake.last_seen_epoch} -> {handshake.resume_epoch}; "
            f"server state is older than client trace"
        )

    return "continuation"
