# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-an-mcp-sse-stream-across-a-server-restart-last-event-id-resumption-and-the-silent-session-generation-mismatch.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-an-mcp-sse-stream-across-a-server-restart-last-event-id-resumption-and-the-silent-session-generation-mismatch.warrant.json
# Markdown SHA-256:   c4c12284c9259ba8508c05daf93bac91691f4d59f739cb61d940a0066ab2ac3c
# Code AST SHA-256:   662b6e93a7d80a1065ae73e7ec3dec6634d531e3badce8e15526e140ea20bee5
# Verified Classes:   StaleSessionResumeError, EventCursor, PendingOperation
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleSessionResumeError(RuntimeError):
    """Raised when an SSE resume would replay events into a dead or mismatched session."""
    pass


@dataclass(frozen=True)
class EventCursor:
    session_generation: int
    seq: int


@dataclass(frozen=True)
class PendingOperation:
    job_id: str
    session_generation: int


def validate_resume(
    last_event_id: Optional[str],
    live_generation: Optional[int],
    pending: Optional[PendingOperation],
) -> EventCursor:
    """
    Decide whether an SSE reconnect may resume.

    last_event_id: raw `Last-Event-ID` header, format "<generation>:<seq>".
    live_generation: generation of the live session table entry, or None if none.
    pending: the operation the client is awaiting, or None.
    """
    if last_event_id is None:
        # Fresh stream, nothing to resume; caller opens a new session.
        if live_generation is None:
            raise StaleSessionResumeError("no cursor and no live session; open fresh session")
        return EventCursor(live_generation, 0)

    try:
        gen_str, seq_str = last_event_id.split(":", 1)
        cursor = EventCursor(int(gen_str), int(seq_str))
    except (ValueError, AttributeError) as exc:
        raise StaleSessionResumeError(f"malformed Last-Event-ID: {last_event_id!r}") from exc

    if live_generation is None:
        # Server restarted; event log may still be replayable, but session is dead.
        # Replaying would fabricate continuity. Fail loudly instead.
        raise StaleSessionResumeError(
            f"cursor generation {cursor.session_generation} has no live session; "
            "refusing to replay into a dead session"
        )

    if cursor.session_generation != live_generation:
        raise StaleSessionResumeError(
            f"cursor generation {cursor.session_generation} != live {live_generation}; "
            "event log and session table lifecycles diverged"
        )

    if pending is not None and pending.session_generation != live_generation:
        raise StaleSessionResumeError(
            f"pending job {pending.job_id!r} bound to generation "
            f"{pending.session_generation}, live is {live_generation}; "
            "re-issue or fail the operation, do not resume"
        )

    return cursor


def correlate_tool_result(event: dict, pending: PendingOperation) -> dict:
    """
    A replayed tool_result is only a completion if it names the pending job.
    Event-type matching alone is the silent-wrong-answer path.
    """
    if event.get("type") != "tool_result":
        raise StaleSessionResumeError(f"unexpected event type {event.get('type')!r} on resume")
    if event.get("job_id") != pending.job_id:
        raise StaleSessionResumeError(
            f"tool_result for job {event.get('job_id')!r} arrived while awaiting "
            f"{pending.job_id!r}; replayed event belongs to a different operation"
        )
    return event
