# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-sse-event-id-replay-from-corrupting-resumable-mcp-sessions-across-stateless-http-servers.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-sse-event-id-replay-from-corrupting-resumable-mcp-sessions-across-stateless-http-servers.warrant.json
# Markdown SHA-256:   4e54767f05adf08363549335d506b1f4cf4c67b2d97f883a9cb075fd97dbfb93
# Code AST SHA-256:   10b67c9567b682c6fc639b889b79b7c186dd470d7ba0ce454a85c5ac2152449d
# Verified Classes:   ResumeContractViolation, SessionEventLog
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class ResumeContractViolation(RuntimeError):
    """Raised when a server attempts to emit or honor an event ID it cannot
    durably serve on an arbitrary replica. This is a hard failure by design:
    the alternative (silent restart or synthetic resume) corrupts the client's
    stream state invisibly."""
    pass


@dataclass
class SessionEventLog:
    """Append-only, replica-readable event log for one MCP session.
    In production this is Redis Streams / Kafka keyed by session_id; here it is
    an in-memory stand-in that enforces the same invariants."""
    session_id: str
    events: list = field(default_factory=list)   # [(event_id, payload)]
    durable: bool = True                          # set False to simulate a stateless replica
    retention_floor: int = 1                      # oldest event ID still replayable

    def last_id(self) -> int:
        return self.events[-1][0] if self.events else 0

    def append(self, payload: dict) -> int:
        # Invariant: write-then-flush. The ID is only returned (and thus only
        # emitted to the client) if the write succeeded durably.
        if not self.durable:
            raise ResumeContractViolation(
                f"replica cannot durably append for session {self.session_id}; "
                f"must not emit event IDs (no-resume regime requires omitting 'id:')"
            )
        next_id = self.last_id() + 1
        self.events.append((next_id, payload))
        return next_id

    def resume_from(self, last_event_id: int) -> list:
        """Return exact successors of last_event_id, or fail loudly. Never
        restart from zero, never synthesize."""
        if last_event_id > self.last_id():
            raise ResumeContractViolation(
                f"client claims Last-Event-ID {last_event_id} but server only "
                f"has up to {self.last_id()}; refusing to fabricate continuation"
            )
        if last_event_id < self.retention_floor - 1:
            raise ResumeContractViolation(
                f"Last-Event-ID {last_event_id} is below retention floor "
                f"{self.retention_floor}; must emit resume_unavailable error event"
            )
        return [e for e in self.events if e[0] > last_event_id]


def handle_resume(log: SessionEventLog, last_event_id: Optional[int]) -> list:
    """Entry point for GET /mcp/session/{sid} with Last-Event-ID header."""
    if last_event_id is None:
        # Client did not ask to resume: fresh stream, no contract to honor.
        return []
    try:
        return log.resume_from(last_event_id)
    except ResumeContractViolation as exc:
        # Do NOT fall back to replay-from-zero or synthetic resume. Surface a
        # terminal error event the client can act on (re-issue with idempotency key).
        raise ResumeContractViolation(
            f"session {log.session_id}: resume to {last_event_id} rejected; "
            f"client must re-issue tools/call with its idempotency key. cause: {exc}"
        ) from exc


# --- trace of the observed failure, now bounded -------------------------------
replica_a = SessionEventLog(session_id="sid-42", durable=True)
for pct in (20, 40, 60, 80, 100):
    replica_a.append({"tool": "fetch", "pct": pct})
# client saw through id=3 (pct=60), then reconnected to a stateless replica:
replica_b = SessionEventLog(session_id="sid-42", durable=False)
try:
    handle_resume(replica_b, last_event_id=3)   # replica B has no log
except ResumeContractViolation as e:
    print(f"BOUNDED: {e}")   # loud failure instead of silent stall / duplicate terminal

# correct path: resume against the durable log
successors = handle_resume(replica_a, last_event_id=3)
assert [e[0] for e in successors] == [4, 5], "gap-free exact continuation"
