# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-against-a-session-token-the-server-has-already-rotated-silent-event-log-divergence-at-the-resu.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-against-a-session-token-the-server-has-already-rotated-silent-event-log-divergence-at-the-resu.warrant.json
# Markdown SHA-256:   beae2ea83ed4e6797e05217c069561a0e178b25277ee71dc262a478e666ca619
# Code AST SHA-256:   7d2ebf4f37306f531060a515bc16777721dfe69be9fbbdcc6494c0cf1a753fab
# Verified Classes:   ResumeRejected, ResumeOutcome, EventLogState, ResumeRequest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum


class ResumeRejected(RuntimeError):
    """Raised when a resume attempt cannot be proven consistent with the current log."""


class ResumeOutcome(Enum):
    REPLAY_FROM_ANCHOR = "replay_from_anchor"
    FULL_RESYNC = "full_resync"


@dataclass(frozen=True)
class EventLogState:
    generation: int
    floor: int          # oldest event id still retained
    max_id: int         # newest event id written


@dataclass(frozen=True)
class ResumeRequest:
    session_token: str
    session_generation: int
    last_event_id: int


def validate_resume(req: ResumeRequest, log: EventLogState) -> ResumeOutcome:
    """
    Enforce the co-versioning invariant: (session token, Last-Event-ID) must
    refer to the same log generation, and the anchor must be representable in
    the current log's [floor, max] range.

    Returns REPLAY_FROM_ANCHOR only when replay is provably continuous.
    Raises ResumeRejected on any inconsistency -- never silently starts fresh.
    """
    if req.session_generation != log.generation:
        # The client holds a token from a prior generation. The server rotated
        # the session (or reinitialized the log) while the client was away.
        raise ResumeRejected(
            f"session generation mismatch: token_gen={req.session_generation} "
            f"log_gen={log.generation}; client must re-negotiate session"
        )

    if req.last_event_id > log.max_id:
        # Client claims to have consumed events the server never wrote.
        # This is the classic 'client ahead of log' case that naive servers
        # treat as 'nothing to replay' and silently restart at 1.
        raise ResumeRejected(
            f"resume anchor {req.last_event_id} exceeds log max {log.max_id}; "
            f"stream state is not representable"
        )

    if req.last_event_id < log.floor - 1:
        # Anchor is older than the eviction floor: events were lost.
        # Partial replay would create a silent gap.
        raise ResumeRejected(
            f"resume anchor {req.last_event_id} below log floor {log.floor}; "
            f"events evicted, full resync required"
        )

    return ResumeOutcome.REPLAY_FROM_ANCHOR


def handle_resume(req: ResumeRequest, log: EventLogState) -> tuple[ResumeOutcome, list[int]]:
    try:
        outcome = validate_resume(req, log)
    except ResumeRejected:
        # Surface as 409 with a machine-readable reason; do NOT emit a stream.
        raise
    replayed = list(range(req.last_event_id + 1, log.max_id + 1))
    return outcome, replayed


# --- Example: the failure trace from the record, replayed against the guard ---

if __name__ == "__main__":
    # Server-side log after the rehydration reset: generation bumped, ids reset.
    current_log = EventLogState(generation=2, floor=0, max_id=0)

    # Worker reconnects holding a gen-1 token and a gen-1 anchor of 4471.
    stale_request = ResumeRequest(
        session_token="sess_8f2a",
        session_generation=1,
        last_event_id=4471,
    )

    try:
        handle_resume(stale_request, current_log)
    except ResumeRejected as exc:
        # Under the guard, the worker never receives a silent renumbered stream.
        # The orchestration layer must now treat the in-flight task as suspect
        # and perform a server-side state read before continuing.
        print(f"resume rejected: {exc}")
        print("action: mark task suspect, re-fetch session state, do not resume from ledger")
