# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-an-mcp-sse-stream-after-a-last-event-id-gap-rather-than-silently-replaying-from-a-stale-cursor.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-an-mcp-sse-stream-after-a-last-event-id-gap-rather-than-silently-replaying-from-a-stale-cursor.warrant.json
# Markdown SHA-256:   06b977905d520611993f456474bb3941f17864f940763074bfba88b39c554546
# Code AST SHA-256:   4a46eeeee0358481a7b32b8a7e064a3251e710e4940bd7a39f3bf63905e2d181
# Verified Classes:   ResumeContiguityError, EventLog
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass


class ResumeContiguityError(RuntimeError):
    """Raised when an MCP SSE resume cannot prove interval-contiguity."""


@dataclass
class EventLog:
    oldest_retained_id: int
    head_id: int
    durable_floor_id: int | None  # lowest ID covered by durable WAL, if any

    def covers(self, last_event_id: int) -> bool:
        # The interval (last_event_id, head_id] must be fully materialized
        # in either the durable log or the ring buffer.
        if last_event_id >= self.head_id:
            return True  # nothing to replay
        if self.durable_floor_id is not None and last_event_id + 1 >= self.durable_floor_id:
            return True  # durable log bridges the eviction hole
        return last_event_id + 1 >= self.oldest_retained_id


def plan_resume(log: EventLog, last_event_id: int) -> int:
    """Return the first event ID to replay, or raise on an unsound resume."""
    if last_event_id < 0:
        raise ResumeContiguityError(f"invalid Last-Event-ID {last_event_id}")
    if last_event_id > log.head_id:
        raise ResumeContiguityError(
            f"Last-Event-ID {last_event_id} is ahead of head {log.head_id}"
        )
    if not log.covers(last_event_id):
        raise ResumeContiguityError(
            "resume gap: Last-Event-ID "
            f"{last_event_id} predates retained interval "
            f"[{log.oldest_retained_id}, {log.head_id}] with no durable coverage; "
            "client must re-issue the original tools/call, not splice"
        )
    return last_event_id + 1


def validate_first_replayed(declared_gap: tuple[int, int] | None,
                            last_event_id: int, first_replayed_id: int) -> None:
    """Client-side contiguity check on the first event of a resumed stream."""
    if declared_gap is not None:
        gap_start, gap_end = declared_gap
        if gap_start != last_event_id + 1 or gap_end >= first_replayed_id:
            raise ResumeContiguityError(
                f"malformed gap declaration {declared_gap} for cursor {last_event_id}"
            )
        return
    if first_replayed_id != last_event_id + 1:
        raise ResumeContiguityError(
            f"non-contiguous resume: expected {last_event_id + 1}, "
            f"got {first_replayed_id}; partial tool-result assembly is unsafe"
        )


# Observed failure, replayed against the guardrail:
log = EventLog(oldest_retained_id=3080, head_id=3190, durable_floor_id=None)
try:
    plan_resume(log, last_event_id=1180)  # the silent-truncation case
except ResumeContiguityError as e:
    print("rejected as expected:", e)
