# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-sse-resumption-token-desynchronization-in-mcp-http-native-transports.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-sse-resumption-token-desynchronization-in-mcp-http-native-transports.warrant.json
# Markdown SHA-256:   83c68324ff39a064025d93b15e684eac8b665990adf8816efa8a302afa134f4c
# Code AST SHA-256:   0f7476e22755eb5c330a87f6a8fc315cbc29e830debeadab414dc599734ed3ad
# Verified Classes:   ResumptionDesyncError, ResumptionLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class ResumptionDesyncError(RuntimeError):
    """Raised when an SSE reconnect violates session-scoped event-ID monotonicity."""
    pass


@dataclass
class ResumptionLedger:
    session_id: str
    last_seen_event_id: int = 0
    pending_request_ids: set = field(default_factory=set)
    # SSE id -> JSON-RPC id mapping established at emit time, never re-derived on replay
    event_to_request: dict = field(default_factory=dict)

    def record_emit(self, sse_id: int, jsonrpc_id: Optional[int]) -> None:
        if sse_id <= self.last_seen_event_id:
            raise ResumptionDesyncError(
                f"non-monotonic emit: sse_id={sse_id} "
                f"<= last_seen={self.last_seen_event_id} in session {self.session_id}"
            )
        self.last_seen_event_id = sse_id
        if jsonrpc_id is not None:
            self.event_to_request[sse_id] = jsonrpc_id

    def accept_reconnect_event(self, sse_id: int, payload_jsonrpc_id: Optional[int]) -> bool:
        """
        Return True iff this event is a valid continuation of the session.
        Return False (caller must buffer/skip) iff it is a pre-gap replay.
        Raise on a future-ID or buffer-gap condition the server failed to signal.
        """
        if sse_id <= self.last_seen_event_id:
            # Pre-gap replay: do NOT attach to any pending request.
            return False
        if sse_id > self.last_seen_event_id + 1:
            # Server resumed past our position without confirming buffer coverage.
            raise ResumptionDesyncError(
                f"resumption gap: expected {self.last_seen_event_id + 1}, "
                f"got {sse_id} in session {self.session_id}; "
                f"server must signal buffer coverage or fail the reconnect"
            )
        # Valid contiguous continuation. Correlate by SSE id, never by JSON-RPC id.
        expected_req = self.event_to_request.get(sse_id)
        if expected_req is not None and payload_jsonrpc_id != expected_req:
            raise ResumptionDesyncError(
                f"correlation mismatch at sse_id={sse_id}: "
                f"expected jsonrpc_id={expected_req}, got {payload_jsonrpc_id}"
            )
        self.last_seen_event_id = sse_id
        return True


def handle_reconnect_stream(ledger: ResumptionLedger, events) -> None:
    """events: iterable of (sse_id, jsonrpc_id, payload)."""
    for sse_id, jsonrpc_id, payload in events:
        if not ledger.accept_reconnect_event(sse_id, jsonrpc_id):
            # Discard stale pre-gap replay; do not feed to the agent's pending slot.
            continue
        ledger.record_emit(sse_id, jsonrpc_id)
        dispatch_to_pending(jsonrpc_id, payload)


def dispatch_to_pending(jsonrpc_id: Optional[int], payload) -> None:
    if jsonrpc_id is None:
        return
    # Real implementation resolves the pending future keyed by the ORIGINAL request id,
    # which is safe only because the ledger has already validated SSE-id contiguity.
    pass
