# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-half-consumed-sse-event-stream-when-an-mcp-streamable-session-resumes-over-a-fresh-http-post.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-half-consumed-sse-event-stream-when-an-mcp-streamable-session-resumes-over-a-fresh-http-post.warrant.json
# Markdown SHA-256:   76e3280c7cd2132a877a0bd8e7a567d9f8fedd90fe88068bcbaf054c7f95134a
# Code AST SHA-256:   1db239ab11c1fa5d6d0a97a63d228ec910736ea1478ab47ea7b0b2f963be50ee
# Verified Classes:   StreamResumptionGap, ChunkAccumulator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class StreamResumptionGap(RuntimeError):
    """Raised when an SSE stream resumed via Last-Event-ID would omit a
    chunk the consumer already acted on, or when the contiguous applied
    offset does not match the server's replay cursor."""


@dataclass
class ChunkAccumulator:
    # Highest contiguous chunk offset the consumer has COMMITTED to state.
    applied_seq: int = -1
    # Frames received but not yet committed (staging buffer).
    staged: dict = field(default_factory=dict)
    terminal_seen: bool = False

    def receive(self, seq: int, payload: str, partial: bool) -> None:
        if seq <= self.applied_seq:
            # Idempotent re-delivery of an already-committed chunk: overwrite.
            return
        self.staged[seq] = (payload, partial)

    def commit_contiguous(self) -> str:
        """Commit only up to the first gap. Never skip a missing seq."""
        out = []
        next_seq = self.applied_seq + 1
        while next_seq in self.staged:
            payload, partial = self.staged.pop(next_seq)
            out.append(payload)
            self.applied_seq = next_seq
            if not partial:
                self.terminal_seen = True
            next_seq += 1
        return "".join(out)


def resume_stream(acc: ChunkAccumulator, last_event_id: int, server_cursor: int) -> None:
    """Called after reconnect. server_cursor is the highest event the server
    believes it delivered (its replay baseline)."""
    if acc.terminal_seen:
        return
    # The server will replay from last_event_id+1, but it considers everything
    # <= server_cursor as delivered. If our contiguous applied offset is below
    # the server's cursor, the frames in between are gone forever.
    if acc.applied_seq < server_cursor and server_cursor > last_event_id:
        raise StreamResumptionGap(
            f"resume would lose chunks {acc.applied_seq + 1}..{server_cursor}: "
            f"applied_seq={acc.applied_seq}, last_event_id={last_event_id}, "
            f"server_cursor={server_cursor}; abort dependent dispatch and retry "
            f"the logical request with an idempotency key"
        )
    # Safe to continue: server cursor is not ahead of our committed state.
    if acc.applied_seq != last_event_id and acc.applied_seq < last_event_id:
        raise StreamResumptionGap(
            f"client committed {acc.applied_seq} but claimed Last-Event-ID "
            f"{last_event_id}; frames between were received but never applied"
        )
