# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-resumption-as-unsafe-after-a-last-event-id-replay-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-resumption-as-unsafe-after-a-last-event-id-replay-gap.warrant.json
# Markdown SHA-256:   abc6a069cae9e18048ad3d627c14a82e859757eb023282ca9d1c30327a61a9f3
# Code AST SHA-256:   d08a5ab23677985a253a49f8920d25ed7723460402cd06550c48ded175171402
# Verified Classes:   StreamResumeGapError, SessionLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StreamResumeGapError(RuntimeError):
    """Raised when a streamable-HTTP reconnect yields a non-contiguous event ID,
    meaning the server's replay buffer evicted events the client never consumed."""
    pass


class SessionLedger:
    def __init__(self, session_id: str):
        self.session_id = session_id
        self.last_seen_id: int | None = None
        self.poisoned = False

    def consume(self, event_id: int, payload: dict) -> None:
        if self.poisoned:
            raise StreamResumeGapError(
                f"session {self.session_id} is poisoned; refusing to apply event {event_id}"
            )
        if self.last_seen_id is not None and event_id != self.last_seen_id + 1:
            self.poisoned = True
            raise StreamResumeGapError(
                f"non-contiguous replay on session {self.session_id}: "
                f"expected id {self.last_seen_id + 1}, got {event_id}; "
                f"events between were evicted from the server ring buffer"
            )
        self.last_seen_id = event_id
        self._apply(payload)

    def _apply(self, payload: dict) -> None:
        # mutate agent belief state only for contiguous events
        ...


def resume_stream(ledger: SessionLedger, first_replayed_id: int) -> None:
    if ledger.last_seen_id is None:
        raise StreamResumeGapError("cannot resume a stream that was never consumed")
    gap = first_replayed_id - ledger.last_seen_id
    if gap > 1:
        ledger.poisoned = True
        raise StreamResumeGapError(
            f"resume gap of {gap - 1} events on session {ledger.session_id}; "
            f"re-execute the originating tools/call instead of splicing replay"
        )
