# Why does an instance lose its MCP stream session when SSE backpressure coalesces the resumption cursor past unflushed tool-call deltas **Date of Record:** 2026 November 28 **Scope:** Applies to MCP servers using HTTP-native transport with Server-Sent Events streaming and `Last-Event-ID`-based session resumption, where a single stream carries tool-call deltas, progress notifications, and result frames. Does not apply to WebSocket transports, stdio transports, or stateless request/response MCP deployments with no resumption contract. ## Core Distinction The failure is not "the connection dropped." Drops are expected and recoverable. The failure is that the **resumption cursor advanced while the frame it referenced was still buffered in the server's SSE write queue**, so on reconnect the client re-requested from a cursor position that had already been acknowledged but whose payload had never left the server. The client believes it resumed correctly; the server believes it delivered. The gap is silent, and it lands precisely on the boundary between a tool call's argument-delta stream and its terminal result frame—the one region where a missing frame produces a *plausible but wrong* reconstruction rather than an obvious parse error. The invariant that breaks: **for any event ID `N` the client has received, the server must guarantee that all events with ID `< N` have been flushed to the socket, not merely assigned.** Under backpressure, event IDs are assigned at enqueue time but flushed at drain time, and these two orderings diverge. ## What Was Observed A client agent issued a `tools/call` for a long-running operation. The server streamed the call as a sequence of SSE frames: an initial `tool_call_start`, a run of `tool_call_delta` frames carrying partial JSON arguments, periodic `progress` notifications, and a final `tool_call_result`. Each frame carried a monotonically increasing `id:` field. The client's TCP receive window filled (a slow consumer—its own downstream model was mid-generation and not reading the socket). The server's SSE writer hit `EAGAIN` and began buffering. The server's event-ID counter, however, kept advancing as frames were *enqueued*, not as they were *written*. The last frame the client actually pulled off the wire before the connection was torn down by an intermediate proxy idle-timeout was event `id: 41` (a `progress` frame). Events 42–47—including two `tool_call_delta` frames and the terminal `tool_call_result`—sat in the server buffer, unflushed. The client reconnected with `Last-Event-ID: 41`. The server, holding its buffer, had already retired those frames from its replay log on the assumption that "enqueued past the cursor means delivered." It resumed the *live* stream at `id: 48`, a subsequent unrelated notification. Events 42–47 were never replayed. The client assembled a tool-call argument object from deltas 1–40 only, missing the two delta frames that closed the JSON object, and—critically—never received the result frame. Its delta-merging logic, tolerant of trailing incompleteness, emitted a truncated-but-parseable argument set and proceeded to act on it. The observable signature: the client's reconstructed tool arguments were a valid JSON object that was *semantically a prefix* of the true arguments. No exception fired. No schema validation failed, because the prefix happened to satisfy the schema's required fields. The corruption was only detectable by comparing against the server's authoritative result, which the client never got. ## Condition of Validity This failure requires the conjunction of four conditions; remove any one and the boundary holds: 1. **Cursor assignment decoupled from flush.** The server assigns `id:` at enqueue, and its replay log's retention watermark advances on enqueue acknowledgment rather than on socket-drain acknowledgment. This is the root cause. Many SSE implementations do this because tracking per-connection flush position is expensive. 2. **Coalescing under backpressure.** The write path batches or drops pending frames when the socket is not writable, so the set of "assigned" IDs strictly exceeds the set of "flushed" IDs at the moment of disconnect. 3. **A frame region where partial delivery is parseable.** Tool-call argument deltas are the canonical case: a prefix of a JSON object is often itself valid JSON, or the client's incremental assembler tolerates it. Progress frames and result frames are not individually parseable-prefix-safe in the same way, which is why the *delta* region is where corruption hides. 4. **Resumption trusts the client-supplied cursor without server-side flush reconciliation.** On reconnect the server replays from `Last-Event-ID` against its *enqueue* log, not against a per-connection *flushed* watermark, so the unflushed frames are considered already-delivered. If the server retains frames until flush is confirmed (condition 1 inverted), or if the client treats any gap in the delta sequence as fatal (condition 3 inverted), the failure cannot occur. ## Decision Boundary The operational decision is: **what does the server's replay log retention watermark track—enqueue or flush?** These are the same under no backpressure and diverge exactly when the consumer is slow, which is exactly when resumption matters. The boundary condition is the moment the socket becomes unwritable while the event-ID counter is live. At that instant: - **Safe side:** the retention watermark is pinned to the highest ID confirmed written to the socket. Frames above it are retained for replay. A reconnect with `Last-Event-ID: 41` replays 42–47 from the buffer, then continues live. The client's assembler sees the complete delta sequence. - **Unsafe side:** the watermark tracks enqueue. Frames above the flushed position are retired. Reconnect resumes at 48. The client's assembler sees a delta gap it cannot distinguish from "the server coalesced deltas as an optimization." The guardrail is a **flush-confirmed watermark** plus a **sequence-continuity assertion on the client**. The server must not advance the replay-retention watermark past the last byte confirmed drained to the socket. The client must reject any delta sequence where the received IDs are not contiguous from its last-known-good cursor, treating a gap as a resumption failure rather than a coalescing optimization. Both are required: the server watermark prevents the loss; the client assertion *detects* the loss if the server watermark is wrong, converting silent corruption into a loud, resumable error. A secondary boundary: **the terminal result frame must be idempotently re-requestable by call ID**, independent of the event-ID cursor. If the client can ask "what was the result of call X" and get an authoritative answer, a lost result frame degrades to a retry rather than a silent truncation. Event-ID resumption alone is insufficient because it makes the result frame's delivery contingent on cursor arithmetic the client cannot audit. ## Operational Effect Without the guardrail, the failure mode is **silent prefix corruption of tool-call arguments under consumer backpressure**, with the corruption rate rising precisely when the client is busiest (slow consumer = backpressure = divergence window). The client proceeds on truncated arguments that pass schema validation because they are a valid prefix, producing downstream actions that are wrong in a way no local check catches. The error surfaces far from its cause—typically as a tool returning a "malformed input" error several reasoning steps later, or worse, as a plausible-but-wrong result the agent accepts. With the flush-confirmed watermark and client-side contiguity assertion, the same backpressure event produces a detectable gap: the client raises a resumption error, reconnects from its last contiguous cursor, and the server replays from its retained buffer. The cost is bounded memory retention proportional to the maximum unflushed backlog—a tunable—rather than silent data loss. The deeper lesson for agent systems: **event-ID cursors are only a resumption contract if ID assignment and delivery are ordered identically.** Any transport that assigns sequence numbers before confirming delivery—SSE, chunked HTTP, message queues with at-least-once semantics—creates a window where the cursor outruns the bytes. For agent tool calls specifically, the delta region makes that window *unobservable* to naive consumers, because partial argument streams are frequently parseable. The invariant to enforce is not "resume from the last ID" but "resume from the last ID whose payload was confirmed flushed, and assert contiguity on receipt." ```python class StreamResumptionGap(RuntimeError): """Raised when a resumed MCP SSE stream skips event IDs that were assigned but never flushed, producing a silent prefix of tool-call argument deltas.""" pass class FlushConfirmedReplayLog: """Replay log whose retention watermark tracks socket flush, not enqueue.""" def __init__(self) -> None: self._frames: dict[int, dict] = {} self._flushed_through: int = 0 # highest ID confirmed written to socket self._assigned_through: int = 0 # highest ID enqueued def enqueue(self, frame: dict) -> int: self._assigned_through += 1 frame_id = self._assigned_through frame["id"] = frame_id self._frames[frame_id] = frame return frame_id def confirm_flushed(self, frame_id: int) -> None: # Advance watermark only on confirmed drain; retain everything above it. if frame_id > self._flushed_through: self._flushed_through = frame_id # Retire only frames strictly below the flushed watermark. for fid in [f for f in self._frames if f < self._flushed_through]: del self._frames[fid] def resume_from(self, last_event_id: int) -> list[dict]: # Replay everything retained above the client's cursor. If the client's # cursor is below the flushed watermark, the gap is unrecoverable here. if last_event_id < self._flushed_through: raise StreamResumptionGap( f"client cursor {last_event_id} precedes flushed watermark " f"{self._flushed_through}; frames were retired before delivery " f"and cannot be replayed" ) return [self._frames[fid] for fid in sorted(self._frames) if fid > last_event_id] def assemble_tool_call_deltas(received_ids: list[int], start_cursor: int) -> None: """Client-side contiguity assertion: a gap in delta IDs is a resumption failure, never a coalescing optimization.""" expected = start_cursor + 1 for fid in received_ids: if fid != expected: raise StreamResumptionGap( f"delta sequence gap: expected id {expected}, received {fid}; " f"tool-call arguments would be silently truncated to a parseable prefix" ) expected += 1 ```