# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-http-session-across-a-mid-stream-reconnect-and-the-last-event-id-cursor-points-into-a-pruned-r.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-http-session-across-a-mid-stream-reconnect-and-the-last-event-id-cursor-points-into-a-pruned-r.warrant.json
# Markdown SHA-256:   30980f65bde9efe37801b9d0076f9df5451014123aaecc9adcbbeff0231f991d
# Code AST SHA-256:   c64dd58270591fc57eb1e98df19aef463be20d21b46e6df68fc96c6df875ec71
# Verified Classes:   ResumptionGapError, ReplayBuffer
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class ResumptionGapError(RuntimeError):
    """Raised when an SSE resumption cursor falls outside the replayable window."""


@dataclass
class ReplayBuffer:
    low_water_mark: int          # earliest event id still resident
    high_water_mark: int         # latest event id emitted
    events: dict[int, str] = field(default_factory=dict)

    def can_satisfy(self, last_event_id: int) -> bool:
        # Cursor is satisfiable iff the next expected event (last+1)
        # is still resident, i.e. last+1 >= low_water_mark.
        return last_event_id + 1 >= self.low_water_mark


def resume_stream(buffer: ReplayBuffer, last_event_id: int) -> list[str]:
    """
    Server-side resumption entry point. Refuses to silently truncate:
    a cursor pointing before the low-water mark is a hard gap.
    """
    expected_next = last_event_id + 1
    if not buffer.can_satisfy(last_event_id):
        raise ResumptionGapError(
            f"Last-Event-ID {last_event_id} precedes replay window "
            f"(earliest available {buffer.low_water_mark}); "
            f"events {expected_next}..{buffer.low_water_mark - 1} are lost. "
            f"Refusing silent truncation; client must restart or reconcile."
        )
    return [buffer.events[i] for i in range(expected_next, buffer.high_water_mark + 1)]


def client_consume(buffer: ReplayBuffer, last_event_id: int, received_ids: list[int]) -> None:
    """
    Client-side contiguity invariant: any forward jump in event IDs
    means the stream is provenance-incomplete, regardless of server flags.
    """
    expected = last_event_id + 1
    for rid in received_ids:
        if rid != expected:
            raise ResumptionGapError(
                f"client observed id {rid}, expected {expected}; "
                f"gap of {rid - expected} event(s) — partial-result cache "
                f"must be invalidated and call marked provenance-incomplete"
            )
        expected += 1


if __name__ == "__main__":
    buf = ReplayBuffer(low_water_mark=57, high_water_mark=88,
                       events={i: f"event-{i}" for i in range(57, 89)})
    # Observed trace: client resumes with cursor 41 against a window starting at 57.
    try:
        resume_stream(buf, last_event_id=41)
    except ResumptionGapError as e:
        print(f"server correctly refused: {e}")
