# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-sse-re-anchoring-loss-during-mcp-http-native-streamable-transport-session-resumption.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-sse-re-anchoring-loss-during-mcp-http-native-streamable-transport-session-resumption.warrant.json
# Markdown SHA-256:   34494eef20985e42b0640079b78bff8d811e397e6faa1a59486d53f73c1a64ed
# Code AST SHA-256:   867627d560b759f7733907967cda30b316b43e8b344369392ccfede7cd8494a4
# Verified Classes:   ResumptionContinuityError, ResumptionLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class ResumptionContinuityError(RuntimeError):
    """Raised when a resumed MCP SSE stream is not contiguous with the client's high-water mark."""
    pass


@dataclass
class ResumptionLedger:
    session_id: str
    last_event_id: int = 0
    last_event_ts: float = 0.0
    server_buffer_depth: int | None = None  # from X-Mcp-Event-Buffer-Depth
    invalidated: set[str] = field(default_factory=set)

    def observe(self, event_id: int) -> None:
        if event_id <= self.last_event_id:
            raise ResumptionContinuityError(
                f"non-monotonic event id {event_id} after {self.last_event_id}"
            )
        self.last_event_id = event_id
        self.last_event_ts = time.time()

    def on_resume(self, first_event_id: int) -> None:
        """Called with the id of the first event on a freshly resumed stream."""
        gap = first_event_id - self.last_event_id - 1
        if gap == 0:
            return  # contiguous; safe to continue
        if self.server_buffer_depth is not None and gap <= self.server_buffer_depth:
            # Server should have replayed but didn't: protocol violation, not a policy limit.
            raise ResumptionContinuityError(
                f"gap of {gap} within advertised buffer depth "
                f"{self.server_buffer_depth}; server failed to replay"
            )
        # Gap exceeds (or unknown against) buffer depth: replay was impossible.
        # Force full invalidation of state observed before the gap.
        self.invalidated.add("*")  # sentinel: all resources and in-flight calls
        raise ResumptionContinuityError(
            f"continuity gap of {gap} events (last={self.last_event_id}, "
            f"head={first_event_id}); all pre-gap state invalidated, re-fetch required"
        )
