# Which invariants prevent SSE replay corruption when MCP HTTP-native streams resume under backpressure **Date of Record:** 2026 November 25 **Scope:** Applies to MCP servers/clients using the HTTP-native transport with Server-Sent Events and `Last-Event-ID`-based session resumption, where the server buffers outbound notifications while a client is slow or disconnected. Does not apply to stdio transport, or to SSE streams that are strictly fire-and-forget with no resumption contract. ## Core Distinction The distinction that matters is between **transport-level resumption** and **protocol-level replay**. `Last-Event-ID` is an HTTP/SSE mechanism: the client says "I last saw event id N, send me what came after." MCP's session semantics require that the *logical* notification stream (tool-list changes, progress notifications, log entries, sampling requests) be delivered exactly once per session and in causal order relative to the client's own requests. The failure mode is that these two contracts are reconciled by a single integer, and under backpressure the integer and the buffer diverge. A server that treats `Last-Event-ID` as a high-water mark into a ring buffer will silently drop events when the buffer has been trimmed, or replay events that were already consumed when the client's `Last-Event-ID` is stale but the buffer still holds them. Neither case is detectable by the client from the SSE frame alone, because SSE frames carry no session-scoped sequence proof. ## What Was Observed A tool-serving MCP server emitted a burst of `notifications/tools/list_changed` and `notifications/progress` frames to a client that had opened a long-lived SSE stream. The client's HTTP read loop stalled (TCP zero-window) for ~40s while a tool call was in flight. During the stall the server's per-session outbound queue grew, then the server applied backpressure by dropping the oldest queued frames to bound memory, advancing a `next_event_id` counter independently of the retained buffer. When the read loop drained, the client reconnected with `Last-Event-ID: 4817`. The server's retained window began at 4850. The server, treating the request as "resume from 4817," clamped to the window start and replayed from 4850 — but the client had already processed frames 4817–4849 before the stall (they were in its kernel receive buffer, not yet read). Result: frames 4850–4859 were delivered twice, and 4817–4849 were never redelivered but *were* processed, so the client's view of `tools/list` oscillated: it applied listing version A (from 4817), then version B (4850), then re-applied B, then received a `progress` notification whose `progressToken` referenced a tool call the client had already completed. The token was unknown, the client emitted an error notification, and the server logged a protocol violation. The non-obvious part: **no frame was lost from the server's perspective, and no frame was lost from the client's perspective.** Both sides believed delivery was complete. The corruption was in *ordering and multiplicity*, not loss. ## Condition of Validity The invariant that would have prevented this is: **the resumption cursor must be a session-scoped monotonic sequence that is (a) never advanced past a frame the server is willing to forget, and (b) never accepted from the client without proof that the client actually consumed up to that cursor.** Two conditions must both hold for `Last-Event-ID` to be safe as an MCP resumption cursor: 1. **Buffer-cursor coupling:** the server must not trim the outbound buffer below the minimum `Last-Event-ID` it will honor. If it must trim for memory, it must *invalidate the session* (force a full re-initialize) rather than serve a clamped replay. A clamped replay is the corruption vector. 2. **Consumption acknowledgment:** the client must only advance `Last-Event-ID` after the frame has been *processed*, not merely *received*. SSE's default `EventSource` advances the id on receipt, which is exactly wrong for a stateful agent whose processing of a `list_changed` frame is asynchronous to its read loop. When either condition fails, the cursor becomes a latency-dependent quantity: it reflects what the client's socket saw, not what the agent's state machine applied. Under backpressure these diverge by an unbounded amount. ## Decision Boundary The boundary is between **clamping** and **failing**. A server under memory pressure has three options when the requested `Last-Event-ID` falls outside the retained window: - **Clamp** (replay from window start): corrupts ordering and multiplicity, as observed. Never correct. - **Drop** (replay from window end): loses frames silently. Never correct. - **Fail the session** (return a resumption error, require re-initialize): correct, because it converts a silent protocol violation into an explicit, client-handleable state transition. The decision rule: if `requested_id < window_start` OR `requested_id > last_emitted_id`, the server MUST reject the resume with a distinct error (e.g., `resumption_unavailable`) and MUST NOT emit any frames on that stream. The client MUST treat that error as a hard session boundary and re-run `initialize` plus any idempotent state re-sync (re-fetch `tools/list`, re-issue in-flight tool calls with fresh tokens). The cost is a cold-start; the alternative is a corrupted agent whose tool registry and progress tokens no longer match the server's. The second boundary: the server must not advance `last_emitted_id` for a frame until that frame is *in the retained buffer*. If the buffer is full and the frame cannot be retained, the server must either block the producer (apply backpressure upstream to the tool execution, not to the SSE stream) or terminate the session. Advancing the cursor while dropping the frame is the exact mechanism that produced the gap. ## Operational Effect With the invariant enforced, the observable behavior changes in three ways: - **Backpressure propagates to the producer, not the stream.** A slow client stalls the tool-execution loop (or its notification emission), not the retention window. The cursor and the buffer stay coupled. - **Resumption is either exact or refused.** There is no third outcome. A client that receives a resume error knows its local view is suspect and must re-sync; a client that receives a successful replay knows every frame from its acknowledged cursor forward is present exactly once. - **The client's acknowledgment is the cursor.** The client's SSE handler buffers frames, applies them to agent state, and only then writes the applied id back as the next `Last-Event-ID`. This makes the cursor a function of agent state, not socket state, which is the only quantity that survives a stalled read loop. The residual risk is that a client crashes between applying a frame and persisting its id. The mitigation is that the applied-id write must be part of the same durable checkpoint as the state mutation the frame caused — otherwise the invariant holds in memory but not across restarts, and the same replay corruption reappears at process boundaries. ```python import time from dataclasses import dataclass, field from typing import Optional class ResumptionInvariantError(RuntimeError): """Raised when an SSE resume request cannot be honored without violating exactly-once, in-order delivery.""" pass @dataclass class OutboundBuffer: window_start: int last_emitted: int frames: dict = field(default_factory=dict) # id -> payload def retain(self, frame_id: int, payload: dict, capacity: int) -> None: # Invariant: never advance last_emitted past a frame we cannot retain. if len(self.frames) >= capacity: raise ResumptionInvariantError( f"buffer at capacity {capacity}; refusing to emit frame {frame_id} " f"without retention (would create a replay gap)" ) if frame_id != self.last_emitted + 1: raise ResumptionInvariantError( f"non-monotonic emission: got {frame_id}, expected {self.last_emitted + 1}" ) self.frames[frame_id] = payload self.last_emitted = frame_id def resume(self, requested_id: int) -> list: # Invariant: exact replay or hard refusal. No clamping, no silent drop. if requested_id < self.window_start: raise ResumptionInvariantError( f"Last-Event-ID {requested_id} precedes retained window " f"start {self.window_start}; session must re-initialize" ) if requested_id > self.last_emitted: raise ResumptionInvariantError( f"Last-Event-ID {requested_id} exceeds last emitted {self.last_emitted}; " f"client cursor is not a valid consumption proof" ) return [self.frames[i] for i in range(requested_id + 1, self.last_emitted + 1) if i in self.frames] def handle_resume(buf: OutboundBuffer, requested_id: Optional[int]) -> list: if requested_id is None: # Fresh stream: client has no cursor, must not receive replay. return [] try: return buf.resume(requested_id) except ResumptionInvariantError: # Convert silent corruption into an explicit session boundary. raise ResumptionInvariantError( "resumption_unavailable: client must re-initialize and re-sync tools/list" ) ```