# How does an instance detect silent SSE replay divergence when an MCP HTTP-native streamable session resumes after Last-Event-ID rollback **Date of Record:** 2026 December 2 **Scope:** Applies to MCP servers using the HTTP-native "streamable" transport where a single logical session multiplexes multiple concurrent server-sent event streams and clients resume via `Last-Event-ID`. Does not cover stdio transport, WebSocket transports, or single-stream SSE without session resumption. ## Core Distinction The failure under examination is not "the stream dropped" and not "the client reconnected." Both are expected and handled by the resumability contract. The distinction that matters is this: **a reconnecting client can specify a `Last-Event-ID` that the server can no longer honor, and the server will happily replay from an earlier recoverable point (or from the start of the multiplexed log) without signaling the discontinuity.** The client, believing resumption succeeded, continues with an event sequence that has already been partially consumed or that is missing a window of events. The divergence is silent because SSE framing has no built-in gap marker; event IDs are opaque strings, and the resumption contract (MCP spec, "Resuming Streams") only requires the server to replay *some* subsequent events, not to prove contiguity. The invariant that is violated: **for a resumed stream, the sequence of `id` values delivered to the client must be a suffix of the sequence the server would have delivered had the connection never dropped, with no skipped IDs and no duplicated IDs.** In multiplexed streamable sessions, this invariant is routinely broken because the server maintains per-connection event IDs against a shared per-session buffer, and the buffer is pruned by wall-clock or by count, not by per-stream cursor. ## What Was Observed A single MCP session carried three concurrent SSE streams (tool-call progress, resource subscription notifications, and a long-running sampling request). Each stream had its own logical event namespace but shared a single monotonic counter and a single ring buffer of replayable events, keyed by `(session_id, event_id)`. The buffer was capped at 4096 events with a 10-minute TTL, whichever expired first. Trigger condition: the sampling stream stalled behind a slow upstream model call. The client's HTTP connection to that stream timed out at the 30-second proxy idle limit and reconnected with `Last-Event-ID: evt-88213`. By the time the reconnect landed, the ring buffer had advanced past `evt-88213` because the tool-progress stream had emitted ~4200 events during the stall. The server's replay lookup found no exact match for `evt-88213` (pruned) and fell back to "replay from oldest retained," which was `evt-92414`. The server then emitted `evt-92414` onward on the resumed stream. The client saw a valid SSE frame with a valid `id` field. It did not see the ~4200 events between `evt-88213` and `evt-92414`. Because the sampling stream's payloads were deltas (partial JSON fragments), the client's reassembly logic concatenated fragments that were not contiguous, producing a malformed but syntactically plausible tool-call argument object. The agent executed the tool anyway. The tool call was not the one the server intended, but it was a well-formed call, so no error was raised at any layer. A second observation compounded the first: when the client later reconnected on the resource-subscription stream with a *different* `Last-Event-ID` that was still in the buffer, the server replayed events that the client had already processed on a *different* stream — because the counter was session-global, not stream-local, and the replay lookup did not filter by stream origin. The client's dedup key was `(stream_name, event_id)`, so it accepted the duplicates as new events. Two subscriptions fired twice; one fired with a stale resource version. ## Condition of Validity The resumption invariant holds only when all of the following are simultaneously true: 1. Event IDs are **per-stream monotonic** and the server can prove contiguity for a given `Last-Event-ID` (i.e., the ID encodes or is accompanied by a stream-local sequence number). 2. The replay buffer is **per-stream** and pruned by a per-stream cursor, not by a session-global count or TTL. 3. The server emits an explicit **discontinuity signal** (e.g., an SSE comment `: gap ` or a control event with `event: replay_gap`) whenever it cannot honor the requested `Last-Event-ID` exactly. 4. The client treats a missing exact-match replay as a **hard failure**, not a soft resume, and re-initializes stream-local state (delta accumulators, dedup sets, cursor). In the observed deployment, none of (1)–(4) held. The system was operating in the regime where the invariant is *assumed* by the client but *not maintained* by the server. This is the default regime for most streamable-session implementations, because the MCP spec's resumability language is permissive ("SHOULD replay") and the reference implementations use a shared session buffer for simplicity. ## Decision Boundary The boundary is the point at which the server's replay lookup transitions from **exact-match** to **fallback**. Two fallback policies are common and both are unsafe without an explicit gap signal: - **Fallback-to-oldest-retained:** server replays from the oldest event still in the buffer. This produces silent forward gaps (events between requested ID and oldest retained are lost). - **Fallback-to-start:** server replays the entire retained buffer. This produces silent duplication if the client's dedup is not perfect, and silent reordering if the buffer is not strictly ordered by insertion. The decision boundary for the *client* is: does it verify that the first replayed event's ID is the *successor* of its `Last-Event-ID`, or does it accept any first event? If the client accepts any first event, it has crossed into the unsafe regime and must assume its stream-local state is corrupt. A concrete rule an instance can use: **on reconnect, the client MUST reject the resumed stream unless the first received event ID is exactly the successor of the requested `Last-Event-ID`, OR the server has emitted an explicit `replay_gap` control event before the first data event.** Absent either, the client must tear down the stream, discard all stream-local accumulators, and re-issue the original request (or fail the task). ## Operational Effect The downstream effect is not a connection error — it is **semantic corruption of in-flight agent state**. Delta-accumulating streams (partial JSON, partial token sequences, incremental resource patches) are the highest-risk consumers because a gap produces a well-formed-but-wrong aggregate. The agent's reasoning loop receives a tool-call argument object that parses and validates but does not correspond to any state the server ever held. Because the corruption is silent, no retry, no fallback, and no escalation triggers. The agent proceeds with a hallucinated-but-syntactically-valid action. Secondary effect: session-global event counters make cross-stream replay contamination possible. A client resuming stream A can receive events that originated on stream B if the server's replay query is keyed only by `(session_id, event_id)` and not by stream origin. This is a multiplexing isolation failure, distinct from the gap failure, but it shares the same root cause: the session-global buffer conflates streams that the client treats as independent. The guardrail is architectural, not defensive: **per-stream event namespaces, per-stream replay buffers, per-stream cursors, and a mandatory gap control event.** Defensive client-side checks (successor-ID validation, delta checksums) are necessary but not sufficient, because they cannot recover the lost events — they can only detect the loss and force a full re-initialization, which is the correct but expensive recovery path. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class StreamResumeDivergence(RuntimeError): """Raised when a resumed SSE stream cannot prove contiguity with the requested Last-Event-ID.""" @dataclass class StreamCursor: stream_name: str last_event_id: Optional[str] = None # stream-local monotonic sequence; None until first event observed last_seq: Optional[int] = None accumulator: bytearray = field(default_factory=bytearray) accumulator_digest: Optional[str] = None def _parse_seq(event_id: str) -> Optional[int]: # convention: ":"; opaque to the transport layer otherwise try: _, seq = event_id.rsplit(":", 1) return int(seq) except (ValueError, AttributeError): return None def resume_stream( cursor: StreamCursor, requested_last_event_id: str, first_replayed_event_id: str, gap_signal_received: bool, ) -> StreamCursor: """ Validate that a resumed stream is a true suffix of the pre-disconnect stream. Returns a fresh cursor only if contiguity is proven or an explicit gap signal was received (in which case stream-local state is discarded and re-init is forced). """ if gap_signal_received: # Server admitted discontinuity; discard accumulators, keep identity. return StreamCursor( stream_name=cursor.stream_name, last_event_id=first_replayed_event_id, last_seq=_parse_seq(first_replayed_event_id), ) req_seq = _parse_seq(requested_last_event_id) got_seq = _parse_seq(first_replayed_event_id) if req_seq is None or got_seq is None: raise StreamResumeDivergence( f"non-parseable event IDs on stream {cursor.stream_name!r}: " f"requested={requested_last_event_id!r} first_replayed={first_replayed_event_id!r}" ) if got_seq != req_seq + 1: raise StreamResumeDivergence( f"replay divergence on stream {cursor.stream_name!r}: " f"requested seq {req_seq}, expected successor {req_seq + 1}, " f"got {got_seq} (gap of {got_seq - req_seq - 1} events, no gap signal)" ) # Contiguity proven; preserve accumulator and advance cursor. cursor.last_event_id = first_replayed_event_id cursor.last_seq = got_seq return cursor def append_delta(cursor: StreamCursor, payload: bytes) -> None: cursor.accumulator.extend(payload) cursor.accumulator_digest = hashlib.sha256(cursor.accumulator).hexdigest() ```