# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-renegotiate-an-mcp-sse-session-after-a-last-event-id-resume-and-why-silent-event-id-reuse-corrupts-tool-call-st.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-renegotiate-an-mcp-sse-session-after-a-last-event-id-resume-and-why-silent-event-id-reuse-corrupts-tool-call-st.warrant.json
# Markdown SHA-256:   77452eef31d8f5db9c7781ddb9d1e48064a8843dac4c4fed2d7f88eb5d0b65e3
# Code AST SHA-256:   7c8b0c0398c042882324b587086fbaf34bf15ee2d696bd5e7a977d3acc287d2d
# Verified Classes:   IncarnationMismatchError, SessionIncarnation, ClientStreamState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import uuid
from dataclasses import dataclass, field
from typing import Optional


class IncarnationMismatchError(RuntimeError):
    """Raised when a resumable SSE resume would splice events across session incarnations."""


@dataclass
class SessionIncarnation:
    session_id: str
    incarnation_token: str = field(default_factory=lambda: str(uuid.uuid4()))
    next_event_id: int = 0


@dataclass
class ClientStreamState:
    session_id: str
    incarnation_token: Optional[str] = None
    last_event_id: int = -1
    partial_buffer: list = field(default_factory=list)


def resume_stream(
    client: ClientStreamState,
    server_session: SessionIncarnation,
    requested_last_event_id: int,
) -> int:
    """
    Validate a Last-Event-ID resume request. Returns the event ID to resume from,
    or raises IncarnationMismatchError if the client must renegotiate instead.
    """
    if client.session_id != server_session.session_id:
        raise IncarnationMismatchError(
            f"session id mismatch: client={client.session_id!r} "
            f"server={server_session.session_id!r}"
        )

    # Fail closed: if the client has no recorded incarnation, it cannot prove
    # continuity, so a transport resume is unsafe.
    if client.incarnation_token is None:
        raise IncarnationMismatchError(
            "client has no incarnation token; cannot prove session continuity"
        )

    if client.incarnation_token != server_session.incarnation_token:
        raise IncarnationMismatchError(
            f"incarnation changed: client={client.incarnation_token} "
            f"server={server_session.incarnation_token}; "
            "client must discard partial buffers and renegotiate "
            "(initialize -> tools/list -> re-issue with idempotency key)"
        )

    if requested_last_event_id >= server_session.next_event_id:
        raise IncarnationMismatchError(
            f"client claims Last-Event-ID={requested_last_event_id} but server "
            f"next_event_id={server_session.next_event_id}; "
            "client is ahead of server or server lost events"
        )

    return requested_last_event_id + 1


def apply_resumed_event(
    client: ClientStreamState,
    event_incarnation_token: str,
    event_id: int,
    payload: dict,
) -> None:
    """Append a resumed event to the client buffer, refusing cross-incarnation splices."""
    if client.incarnation_token is None:
        client.incarnation_token = event_incarnation_token
    elif client.incarnation_token != event_incarnation_token:
        raise IncarnationMismatchError(
            f"refusing to splice event {event_id} from incarnation "
            f"{event_incarnation_token} onto buffer from "
            f"{client.incarnation_token}; discard buffer and renegotiate"
        )
    client.partial_buffer.append(payload)
    client.last_event_id = event_id
