# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-sse-last-event-id-resumption-as-a-new-session-rather-than-a-continuation-and-what-breaks-if-it-doesn-t.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-sse-last-event-id-resumption-as-a-new-session-rather-than-a-continuation-and-what-breaks-if-it-doesn-t.warrant.json
# Markdown SHA-256:   71133f5623ed898941e789a113e623a5797255f791dddc047926083deb9200b1
# Code AST SHA-256:   9e7839ca99748b91777fb22358fd676c13d7be029270e51f8ac3954091fef0cc
# Verified Classes:   SessionResumptionViolation, SessionRecord, ClientState
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SessionResumptionViolation(RuntimeError):
    """Raised when an SSE resumption would splice events across a session boundary."""
    pass


@dataclass
class SessionRecord:
    session_id: str
    generation: int
    live: bool
    replay_window_end: int          # highest event id retained for this session
    grace_expires_at: float         # monotonic seconds
    pending_requests: set[str] = field(default_factory=set)


@dataclass
class ClientState:
    session_id: str
    generation: int
    last_event_id: int
    resolved_requests: set[str] = field(default_factory=set)


def validate_resumption(
    server: dict[str, SessionRecord],
    client: ClientState,
    presented_session_id: str,
    presented_last_event_id: int,
    now: float,
) -> SessionRecord:
    rec = server.get(presented_session_id)

    # 1. Session must exist and be live (not evicted, not merely in grace).
    if rec is None or not rec.live:
        raise SessionResumptionViolation(
            f"session {presented_session_id!r} is not live; "
            f"resumption must be rejected and client re-initialized"
        )

    # 2. Grace window must not have lapsed even if the replay buffer still holds events.
    if now >= rec.grace_expires_at:
        raise SessionResumptionViolation(
            f"session {presented_session_id!r} grace expired at {rec.grace_expires_at}; "
            f"replay buffer presence is not sufficient for continuation"
        )

    # 3. Session generation must match the client's held generation.
    if rec.generation != client.generation:
        raise SessionResumptionViolation(
            f"session generation mismatch: server={rec.generation} client={client.generation}; "
            f"cursor is stream-scoped, not session-scoped"
        )

    # 4. Cursor must be within this session's replay window.
    if presented_last_event_id > rec.replay_window_end:
        raise SessionResumptionViolation(
            f"Last-Event-ID {presented_last_event_id} exceeds session replay window "
            f"{rec.replay_window_end}; cannot reconstruct causal frontier"
        )

    # 5. Client must not be ahead of the server's frontier (divergence, not resumption).
    if client.last_event_id > presented_last_event_id:
        raise SessionResumptionViolation(
            f"client frontier {client.last_event_id} is ahead of resumed frontier "
            f"{presented_last_event_id}; this is divergence, not continuation"
        )

    # 6. Replayed progress for already-resolved requests is a duplicate-execution hazard.
    overlap = rec.pending_requests & client.resolved_requests
    if overlap:
        raise SessionResumptionViolation(
            f"replay would resurrect resolved requests {sorted(overlap)}; "
            f"duplicate side effects possible"
        )

    return rec
