# Which invariants prevent resumption replay divergence across stateless MCP streamable-SSE replicas **Date of Record:** 2026 November 28 **Scope:** Applies to MCP servers using the HTTP-native streamable transport where a single logical session's SSE stream may be resumed via `Last-Event-ID` against a stateless (or effectively stateless) serverless backend. Does not apply to single-process stateful servers that hold the event buffer in memory for the session lifetime. ## Core Distinction The distinction that matters is between **transport-level resumption** and **application-level replay**. The MCP streamable HTTP transport defines resumption as: a client whose SSE connection drops reconnects with `Last-Event-ID: ` and the server continues the stream *after* that event. This is a transport guarantee about byte/event ordering. It is **not** a guarantee that the tool execution that produced those events will not run again, nor that the server can reconstruct which events it already emitted. In a stateless serverless deployment, the replica handling the reconnect is almost never the replica that produced the original stream, and holds no in-memory record of emitted event IDs. The invariant that must hold is: *the set of events a client observes across a resumption is exactly the sequence the logical operation would have produced, with no gaps and no duplicates, regardless of which replica serves the reconnect.* That invariant is not provided by the transport; it must be constructed. ## What Was Observed A tool call `analyze_dataset` streamed progress events `evt-1 … evt-9` over SSE. The client connection dropped after receiving `evt-6`. The client reconnected with `Last-Event-ID: evt-6` to the load balancer, which routed to a cold replica (scale-to-zero had recycled the original). The cold replica had no event log. Its handler, on seeing a resume request it could not satisfy, did the locally reasonable thing: it **re-executed the tool from the start** and began emitting a fresh stream `evt-1' … evt-9'`. The client, honoring the transport contract, appended everything after `evt-6`, yielding the observed sequence: ``` evt-1 evt-2 evt-3 evt-4 evt-5 evt-6 evt-1' evt-2' ... evt-9' ``` Two failure classes surfaced simultaneously. First, **duplicate side effects**: the tool had already mutated external state during the first run (wrote a partial artifact, appended rows), and the replay mutated it again. Second, **divergent content**: the second run was non-deterministic (sampling temperature, a live data source that had changed), so `evt-4'` carried a different intermediate value than `evt-4`. The client's reconstructed view was internally inconsistent—it had the *tail* of run A and the *whole* of run B stitched together, with `evt-6` (from A) directly preceding `evt-1'` (from B). No single execution ever produced that sequence. Downstream, an agent reasoning over the streamed progress concluded the dataset had been processed twice with conflicting results. The non-obvious part: the cold replica's behavior was *correct per the transport spec*. The spec says the server SHOULD replay missed events; it does not mandate that the server be able to. When it cannot, re-running is a legal fallback. The divergence is produced by the *composition* of a legal fallback with a legal client-side append, not by any single party violating its contract. ## Condition of Validity Reconnect-with-replay is only sound when all three hold: 1. **Event identity is globally unique and monotonic across replicas**, not per-connection counter values. `evt-1` from replica A and `evt-1` from replica B must not collide. Use a session-scoped monotonic sequence (e.g., `{session_id}:{seq}`) minted at the point of side effect, not at the point of emission. 2. **The event log is durable and shared** across replicas for at least the resumption window (a TTL ≥ max client reconnect backoff). Without this, a cold replica cannot distinguish "resume from evt-6" from "start fresh," and will guess wrong. 3. **Tool execution is idempotent or checkpointed** at event boundaries, so that re-execution after `evt-6` produces identical `evt-7…9` and does not re-fire side effects already committed for `evt-1…6`. When any of the three is absent—the common case for naive scale-to-zero deployments—the transport's "SHOULD replay" degrades into "MAY re-run," and the client's append-on-resume turns that into silent duplication. The invariant is only valid under all three; it is not a property you get for free by using the streamable transport. ## Decision Boundary The boundary is **whether the server can prove it has already emitted up to `Last-Event-ID`**. Concretely: - If the durable event log contains an entry for `Last-Event-ID` **and** the operation's checkpoint at that sequence is intact → **resume**: stream `seq+1 …` from the log or from the checkpoint, do not re-execute committed steps. - If the log has the ID but the checkpoint is gone → **fail closed**: return a resumption error the client can act on (e.g., 409 with a resume-token), do **not** silently re-run. The client must decide whether to restart the logical operation with a new session ID. - If the log has no entry for the ID (cold replica, expired TTL, or a forged/stale ID) → **fail closed** with the same error. Never treat "unknown ID" as "start from zero," because the client will append. The anti-pattern is exactly the observed one: mapping "unknown `Last-Event-ID`" to "re-execute and emit from `evt-1`," because the client's transport layer has no way to detect the seam and will splice the two runs. A second anti-pattern is emitting per-connection counters so that `evt-1` is reused, defeating the client's ability to dedupe. ## Operational Effect With the invariant enforced, resumption becomes *safe to retry*: a dropped stream either continues exactly where it left off (no gap, no duplicate) or fails loudly with a resumption error that the agent layer can route to a fresh session. The cost is that the event log and per-event checkpoint must outlive the connection and be reachable from any replica—which pushes the deployment from "truly stateless" to "stateless compute over a durable session store," a materially different architecture. Teams that skip this get the failure above: occasional, non-deterministic, hard-to-reproduce stream corruption that only manifests under connection drops during non-idempotent tool calls, and that looks like a client bug because every individual component obeyed its contract. The guardrail is to treat `Last-Event-ID` as a **claim requiring proof**, not a hint, and to make the "cannot prove" path a hard error rather than a re-run. ```python class ResumptionDivergenceError(RuntimeError): """Raised when a resume request cannot be satisfied without risking duplicate side effects or a spliced event sequence.""" pass def resume_stream(session_id: str, last_event_id: str, event_log, checkpoint_store): seq = parse_seq(last_event_id) # "sess:7" -> (sess, 7); raises on malformed # Invariant 1: identity must be session-scoped and match this session. if seq.session != session_id: raise ResumptionDivergenceError( f"Last-Event-ID {last_event_id!r} belongs to session {seq.session!r}, " f"not {session_id!r}; refusing to splice streams." ) # Invariant 2: the event must actually exist in the durable log. if not event_log.contains(session_id, seq.n): # Cold replica / expired TTL / forged id. Do NOT fall back to re-run: # the client will append, producing evt-1..6 + evt-1'..N'. raise ResumptionDivergenceError( f"No durable record of {last_event_id!r} for session {session_id!r}; " f"cannot prove emission. Client must restart with a new session." ) # Invariant 3: the checkpoint at that boundary must be intact so that # re-emitting seq+1.. does not re-fire committed side effects. if not checkpoint_store.is_intact(session_id, seq.n): raise ResumptionDivergenceError( f"Checkpoint for {last_event_id!r} missing or torn; " f"re-execution would duplicate side effects." ) # Sound path: continue strictly after the proven boundary. return event_log.stream_after(session_id, seq.n) ```