# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-last-event-id-replay-windows-with-a-saturated-sse-buffer-during-mcp-stream-resumption.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-last-event-id-replay-windows-with-a-saturated-sse-buffer-during-mcp-stream-resumption.warrant.json
# Markdown SHA-256:   623723be2c9bbb55bdad7777705c2c4d2df01a1111fe73dc167c35e533d9ed19
# Code AST SHA-256:   c6fc24cca9a831baef7c9d4d77ffb6f09a6ed31cdf8b70fdebf8ecdfbb14c910
# Verified Classes:   SSEStreamContiguityError, ContiguityLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class SSEStreamContiguityError(RuntimeError):
    """Raised when an SSE event violates the expected-next-ID invariant.

    Indicates either in-flight event loss (dropped before ID assignment) or a
    replay-log gap. The session must be quarantined; the event payload must NOT
    be admitted to the agent context.
    """


@dataclass
class ContiguityLedger:
    """Tracks expected next event ID across live ingest and resume.

    The ledger is the only source of truth for stream continuity. It is advanced
    strictly by received_id + 1 and never by a server-supplied last-event-id.
    """

    expected_next: int
    quarantine_reason: str | None = None
    _seen: set[int] = field(default_factory=set)

    def ingest(self, received_id: int) -> None:
        if self.quarantine_reason is not None:
            raise SSEStreamContiguityError(
                f"session quarantined: {self.quarantine_reason}"
            )
        if received_id in self._seen:
            # Duplicate replay after resume is legal; drop silently.
            return
        if received_id != self.expected_next:
            self.quarantine_reason = (
                f"gap detected: expected id {self.expected_next}, "
                f"received id {received_id}"
            )
            raise SSEStreamContiguityError(self.quarantine_reason)
        self._seen.add(received_id)
        self.expected_next += 1

    def resume_from(self, last_event_id: int) -> None:
        """Called on reconnect. Server must replay from last_event_id + 1."""
        if last_event_id + 1 != self.expected_next:
            self.quarantine_reason = (
                f"resume mismatch: server asked to resume from {last_event_id}, "
                f"ledger expects {self.expected_next}"
            )
            raise SSEStreamContiguityError(self.quarantine_reason)


def admit_event(ledger: ContiguityLedger, event_id: int, payload: dict) -> dict:
    """Admit an SSE event into agent context only if contiguity holds."""
    ledger.ingest(event_id)
    return payload
