# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-sse-event-id-replay-as-a-session-integrity-violation-rather-than-a-resumable-continuation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-sse-event-id-replay-as-a-session-integrity-violation-rather-than-a-resumable-continuation.warrant.json
# Markdown SHA-256:   18e791a2c1c194c26cbeaaec7d31e3a60977f1f2e507b80d8123a803665292cc
# Code AST SHA-256:   b6d57cd1fe69d8d7d32c0554b6a87e6cf9b46b63f8c24c9c23545119d70fab48
# Verified Classes:   SessionIntegrityViolation, SessionRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SessionIntegrityViolation(RuntimeError):
    """Raised when a replayed MCP SSE frame claims continuity but contradicts
    already-consumed session state (cross-epoch splice or corrupted cursor)."""
    pass


@dataclass
class SessionRecord:
    epoch: str
    last_event_id: int
    consumed_call_tokens: set[str] = field(default_factory=set)
    terminal_call_tokens: set[str] = field(default_factory=set)


def resume_or_reestablish(
    record: SessionRecord,
    server_epoch: str,
    first_replayed_id: int,
    frame: dict,
) -> str:
    """Decide how to handle a reconnect. Returns 'resume' | 'reestablish'.
    Raises SessionIntegrityViolation when the frame claims continuity but
    contradicts the client's record of this epoch."""
    if server_epoch != record.epoch:
        # Different causal history; the cursor is meaningless here.
        return "reestablish"

    if first_replayed_id != record.last_event_id + 1:
        # Gap the server cannot account for within the same epoch.
        return "reestablish"

    token = frame.get("params", {}).get("progressToken")
    method = frame.get("method", "")

    if method == "notifications/progress" and token in record.terminal_call_tokens:
        raise SessionIntegrityViolation(
            f"progress frame for token {token!r} after its terminal result "
            f"in epoch {record.epoch!r}; replay claims continuity but "
            f"contradicts consumed state (likely cross-epoch splice)"
        )

    if method == "notifications/progress" and token not in record.consumed_call_tokens:
        raise SessionIntegrityViolation(
            f"progress frame for token {token!r} never issued in epoch "
            f"{record.epoch!r}; cursor or epoch token is corrupt"
        )

    return "resume"
