# When must an instance refuse to resume an SSE stream after migrating to Streamable HTTP: the Last-Event-ID replay window invariant **Date of Record:** 2026 November 29 **Scope:** Applies to MCP servers that expose both the legacy HTTP+SSE transport (`GET /sse` + `POST /messages`) and the Streamable HTTP transport (`POST /mcp` with `Mcp-Session-Id`), and to clients that attempt to carry an in-flight SSE session across that boundary using `Last-Event-ID` and `Mcp-Session-Id` continuity. Does not apply to pure stdio transports or to servers that never emit resumable event IDs. ## Core Distinction The failure is not "the stream dropped." Dropped streams are routine and the SSE spec's `Last-Event-ID` resumption mechanism exists precisely for them. The failure is a **category error at the transport boundary**: a client treats `Last-Event-ID` as a session-scoped cursor that survives a change of transport, when in the Streamable HTTP transport the event ID namespace is bound to the *session object*, not to the *connection*. When an agent migrates from `/sse` to `/mcp`, it is asking the server to replay events from a cursor that was minted by a different session's event log. The server has two legal responses and one illegal-but-common one: - **Legal:** reject with a session-mismatch error, forcing a fresh `initialize`. - **Legal:** accept and replay from a *shared, monotonic* event log that spans both transports. - **Illegal but frequently observed:** accept the `Last-Event-ID`, silently serve events from the new session's log starting at whatever offset the cursor happens to index, and drop the gap. The dangerous case is the third, because it looks like a successful resume. The agent resumes mid-task believing it has full continuity, but the events between the old session's last delivered ID and the new session's first available ID are gone — and no error was raised. ## What Was Observed A long-running agent tool-call loop (a "fetch-and-summarize" task spanning ~40 tool invocations) was executing over `GET /sse`. The server emitted events with IDs of the form `sse-`. At event `sse-1841` the underlying connection was severed by a load balancer idle timeout (60s, no keepalive configured). The client had been configured with a migration policy: on SSE failure, attempt Streamable HTTP with the same logical session. Trace: 1. `GET /sse` connection reset at event `sse-1841`. Client has `lastEventId = "sse-1841"`. 2. Client opens `POST /mcp` with headers `Mcp-Session-Id: `, `Last-Event-ID: sse-1841`. 3. Server's Streamable HTTP handler parses `Last-Event-ID`, strips the `sse-` prefix, gets integer `1841`, and looks it up in the *Streamable HTTP session's* event ring buffer. 4. The Streamable HTTP session was created lazily at step 2 and its ring buffer is indexed by a *per-session* counter starting at `0`. The buffer currently holds events `0..2` (the `initialize` response and two notifications). `1841` is out of range. 5. Server's range check was `if id > oldest_retained: replay_from(id)` — a classic off-by-direction bug. Since `1841 > 0`, the check passed. 6. Server replayed zero events (nothing `>= 1841` existed) and returned `200 OK` with an empty replay followed by live streaming. 7. The agent received `200 OK`, concluded resumption succeeded, and continued its loop — but it had lost the three events emitted between `sse-1841` and the session teardown, including one `tool_result` containing the output of a `fetch` call the agent was about to summarize. 8. The agent proceeded to summarize a `tool_result` it had never received, hallucinating the content from the prior `tool_call` arguments, and wrote a corrupted artifact. The corruption was silent. No 4xx, no `error` event, no log line. The only signal was downstream: the summary contradicted the (unseen) fetch output. ## Condition of Validity The resumption is valid **iff** the event-ID space is shared and monotonic across the transport transition, or the server explicitly signals a non-resumable gap. Formally, let `E_old` be the ordered event log of the SSE session and `E_new` that of the Streamable HTTP session. A resume with cursor `c` is sound iff there exists a total order `≺` over `E_old ∪ E_new` such that: - `c ∈ E_old` and `c` is the last event the client *acknowledged processing*; - every event `e ∈ E_old ∪ E_new` with `c ≺ e` is either replayed or explicitly reported as unavailable; - no event is skipped without an explicit gap marker. The observed server violated the third clause. Its range check `id > oldest_retained` only guards against replaying *too far back* (evicted events); it does not guard against a cursor that is *ahead* of the new session's head, which is the actual failure mode when migrating from a long-lived SSE session into a freshly minted Streamable HTTP session. The invariant the server *should* have enforced: **a `Last-Event-ID` is only meaningful within the session that minted it.** If `Mcp-Session-Id` differs from the session that issued the cursor, or if the cursor exceeds the new session's high-water mark, the server must reject with a resumability error rather than serve an empty replay. ## Decision Boundary The agent-side decision boundary is crisp: **on any transport migration, treat `Last-Event-ID` as untrusted until the server proves the cursor is live in the new session's log.** Concretely, before resuming the task loop, the agent must confirm one of: - the server returned a non-empty replay whose first event ID equals `lastEventId + 1` (contiguous), or - the server returned an explicit `gap` / `resumability_lost` signal, in which case the agent must re-derive state from a checkpoint, not from the stream. An empty replay after a migration is **not** a success signal — it is the ambiguous case and must be treated as a failure until proven otherwise. The agent cannot distinguish "no events happened while you were away" from "we lost your cursor" from the wire alone, so it must not guess. The server-side boundary: the range check must be `oldest_retained <= id <= high_water_mark`, with an explicit `resumability_lost` error for `id > high_water_mark`. The `id > oldest_retained` check is a bug, not a policy. ## Operational Effect Without this invariant, agents exhibit a specific and reproducible pathology: **silent state divergence at transport boundaries**, manifesting as hallucinated tool outputs. The agent's reasoning loop is sound given its (corrupted) belief state; the corruption happened at the transport layer and was laundered through a `200 OK`. Because the failure is silent, it is not caught by retry logic, not caught by error-rate monitoring, and only surfaces as downstream artifact inconsistency — often attributing blame to the model rather than the transport. The fix is cheap on both sides: servers must reject out-of-range cursors with a typed error; clients must treat empty-replay-after-migration as a checkpoint-invalidation trigger. The cost of the bug is a corrupted task; the cost of the fix is one comparison and one branch. ```python from dataclasses import dataclass class ResumabilityLost(RuntimeError): """Raised when a Last-Event-ID cannot be honored in the target session.""" @dataclass(frozen=True) class EventLog: session_id: str oldest_retained: int high_water_mark: int # last event ID ever minted in this session def can_resume(self, cursor: int) -> bool: return self.oldest_retained <= cursor <= self.high_water_mark def resume_stream( log: EventLog, cursor: int, cursor_session_id: str, ) -> list[int]: """ Validate a resume request against the target session's event log. Invariant: a cursor is only resumable within the session that minted it, AND only if it lies within [oldest_retained, high_water_mark]. A cursor ahead of the high-water mark means the client is migrating from a different (or torn-down) session and the intervening events are gone. """ if cursor_session_id != log.session_id: raise ResumabilityLost( f"cursor minted by session {cursor_session_id!r} cannot resume " f"session {log.session_id!r}" ) if cursor > log.high_water_mark: raise ResumabilityLost( f"cursor {cursor} exceeds high-water mark {log.high_water_mark}; " f"events in ({log.high_water_mark}, {cursor}] are unavailable" ) if cursor < log.oldest_retained: raise ResumabilityLost( f"cursor {cursor} predates oldest retained event " f"{log.oldest_retained}; replay window evicted" ) return list(range(cursor + 1, log.high_water_mark + 1)) def migrate_and_resume( new_session: EventLog, last_event_id: str, last_event_session: str, ) -> list[int]: """ Client-side entry point for SSE -> Streamable HTTP migration. Parses the cursor and enforces the invariant. Empty replay is NOT treated as success — the caller must reconcile against a checkpoint. """ prefix = "sse-" if not last_event_id.startswith(prefix): raise ResumabilityLost(f"unparseable Last-Event-ID: {last_event_id!r}") cursor = int(last_event_id[len(prefix):]) replayed = resume_stream(new_session, cursor, last_event_session) if not replayed: # No events between cursor and head. This is the ambiguous case: # we cannot distinguish "nothing happened" from "we lost the gap". # Force checkpoint reconciliation rather than silently continuing. raise ResumabilityLost( f"empty replay after migration (cursor={cursor}); " f"reconcile agent state from checkpoint before continuing" ) return replayed ```