# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-an-mcp-sse-stream-against-a-session-affinity-router-that-has-already-rebalanced-the-session.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-an-mcp-sse-stream-against-a-session-affinity-router-that-has-already-rebalanced-the-session.warrant.json
# Markdown SHA-256:   85481fc7b8a0284eeb0780137cd1a38a955e938e641956cb3b63568d8e9a8ad2
# Code AST SHA-256:   2450547888d613c1a0259dfc7a3255304060e82802b84425d8bd220da9b242a6
# Verified Classes:   SessionDiscontinuity, ReplayEvent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SessionDiscontinuity(RuntimeError):
    """Raised when an MCP SSE resumption violates session continuity."""
    pass


@dataclass(frozen=True)
class ReplayEvent:
    event_id: int
    payload: bytes

    def payload_hash(self) -> str:
        return hashlib.sha256(self.payload).hexdigest()


def validate_resumption(
    last_event_id: int,
    replayed: list[ReplayEvent],
    prior_hashes: dict[int, str],
) -> None:
    """
    Enforce the continuity invariant on an SSE resumption.

    prior_hashes maps event_id -> payload_hash for events already
    observed on the pre-disconnect stream. Any replayed event whose
    ID is <= last_event_id with a *different* payload hash indicates
    a forked event log (affinity rebalanced to a divergent replica).
    Any replayed event whose ID is strictly less than the first
    expected ID indicates a restarted log (lazy-init replica).
    """
    if not replayed:
        raise SessionDiscontinuity(
            f"empty replay after Last-Event-ID={last_event_id}; "
            "server likely initialized a fresh log"
        )

    first = replayed[0].event_id
    if first <= last_event_id and first != last_event_id + 1:
        # Server restarted its log at 1, or jumped backward.
        raise SessionDiscontinuity(
            f"replay began at id={first} after Last-Event-ID={last_event_id}; "
            "monotonicity violated — session forked or log restarted"
        )

    for ev in replayed:
        prior = prior_hashes.get(ev.event_id)
        if prior is not None and prior != ev.payload_hash():
            raise SessionDiscontinuity(
                f"event id={ev.event_id} replayed with divergent payload "
                f"(prior={prior[:12]} now={ev.payload_hash()[:12]}); "
                "affinity miss to a replica with a forked event log"
            )


def resume_session(
    session_id: str,
    last_event_id: int,
    fetch_replay,
    prior_hashes: dict[int, str],
) -> list[ReplayEvent]:
    replayed = fetch_replay(session_id, last_event_id)
    if replayed is None:
        raise SessionDiscontinuity(
            f"server returned 404 for session {session_id[:8]}...; "
            "task must restart from last durable checkpoint"
        )
    validate_resumption(last_event_id, replayed, prior_hashes)
    return replayed
