# Why does an instance resume an MCP stream against a session token whose event history has already been compacted? **Date of Record:** 2026 November 29 **Scope:** Applies to MCP servers migrating from the legacy HTTP+SSE transport to streamable HTTP with `Mcp-Session-Id` and `Last-Event-ID` resumption. Does not apply to stdio transport, nor to stateless streamable-HTTP deployments that never issue session IDs. ## Core Distinction The legacy SSE transport and the streamable-HTTP transport both carry a session identifier, but they assign it *different semantics of continuity*. In legacy HTTP+SSE, the session ID is a **connection-scoped handle**. It names a live SSE channel bound to one open `GET /sse` response. If the channel dies, the session dies with it; a reconnect opens a new channel and the client is expected to rebuild state from scratch. The ID is effectively a liveness token — it points at a socket, not at a log. In streamable HTTP, the session ID is a **log-scoped cursor anchor**. `Mcp-Session-Id` names a durable server-side event history, and `Last-Event-ID` names a position *within* that history. Resumption is a replay request: "give me everything after event N." The ID now points at a retained buffer, not at a socket. The boundary failure lives exactly at the seam where a client keeps the legacy mental model (session = live channel, resume = reconnect) while the server has adopted the new one (session = retained log, resume = replay from cursor). An instance that reconnects with a valid `Mcp-Session-Id` and a `Last-Event-ID` pointing *before the server's compaction watermark* is not "reconnecting." It is asking for events the server has already discarded to bound memory. The server cannot honor it and cannot honestly refuse it as "unknown session" — the session is real, the cursor is real, only the *events between them* are gone. ## What Was Observed A single-node MCP server was migrated from SSE to streamable HTTP. The server retained per-session event history in a ring buffer keyed by `Mcp-Session-Id`, each event stamped with a monotonic `id`. To bound memory, the buffer evicted events older than the last 512 entries per session, advancing a per-session `compaction_watermark` (the highest evicted event ID). Sessions themselves were retained for 30 minutes past last activity. The failure trace, reproduced against a tool-calling agent that issued long-running `tools/call` requests: 1. Agent opens session `S`, sends `initialize`, receives `Mcp-Session-Id: S`. Server assigns `last_event_id = 0`. 2. Agent begins a multi-step plan; each tool result is streamed as an SSE event on the session's stream. Events accrue IDs `1..N`. 3. The agent's HTTP client hits a transient TCP reset mid-stream (common under mobile/NAT churn). The client's reconnect logic — carried over unchanged from the SSE era — reconnects with `Mcp-Session-Id: S` and `Last-Event-ID: k`, where `k` is the last event it *successfully parsed*, not the last the server emitted. 4. Meanwhile the server, under load from other sessions, has evicted events `1..m` where `m > k`. The session is alive; `compaction_watermark = m`. 5. Server receives `Last-Event-ID: k < m`. It has three plausible behaviors, and the bug is that it silently picks the worst one: it treats "cursor before watermark" as "cursor at watermark," replays from `m+1`, and emits a fresh `200` stream. The agent resumes with an apparently valid stream that is **missing events `k+1..m`** — which in this trace included the `result` payloads of two completed `tools/call` requests and one `notifications/progress` that the agent used to decide whether to retry. 6. The agent, seeing no result for tool call #2, re-issues it. The tool is non-idempotent (a write). Result: duplicated side effect, and a reasoning trace that now believes tool #2 succeeded twice with divergent outputs. The observable signature was a gap in the agent's event sequence that the transport layer reported as *success*. No error, no `4xx`, no gap marker. The stream simply began at `m+1`. ## Condition of Validity The invariant the transport layer *must* enforce, and which the naive migration violates: > A resumption request whose `Last-Event-ID` is strictly less than the session's `compaction_watermark` MUST be rejected as unrecoverable, not silently clamped to the watermark. This is a **continuity invariant**, and it is violated by the single most natural line of code in a streamable-HTTP server: ``` start = max(last_event_id, compaction_watermark) + 1 # WRONG ``` The correct form refuses: ``` if last_event_id < compaction_watermark: raise UnrecoverableGap(...) start = last_event_id + 1 ``` The failure is only reachable when three conditions co-occur, which is why it survives casual testing: - The session is still alive (so the server does not return `404` for an unknown session — the legacy path would have caught it). - The eviction watermark has advanced past the client's cursor (requires enough event volume or a slow client, i.e., a *long* disconnect relative to buffer churn). - The client's reconnect logic is inherited from the SSE era and treats any `200` stream as "resumed correctly" (the SSE client had no notion of a gap because the channel *was* the state). Remove any one and the bug is invisible. This is precisely the class of failure that a migration produces: each component is individually correct under its own model, and the model boundary is unguarded. ## Decision Boundary The operational fork is: **when a resumption cursor precedes the compaction watermark, does the server (a) clamp and continue, (b) terminate the session and force re-initialization, or (c) reject the resume with an explicit unrecoverable-gap signal?** - **(a) Clamp** is only safe if the protocol guarantees that no event the client needs for correctness can be evicted while the client's cursor is behind. That guarantee does not exist for `tools/call` results, because the agent's cursor advances only on *parsed* events, and parsing can lag emission arbitrarily. Clamping is therefore safe only for pure-notification streams with no causal payloads — a condition almost no real MCP server satisfies. - **(b) Terminate the session** is correct but expensive: it forces full re-`initialize`, re-negotiation of capabilities, and loss of any server-side session state. It is the right choice when the session holds no state that cannot be rebuilt, and it is the *safe default* for a server that cannot prove otherwise. - **(c) Explicit unrecoverable-gap rejection** is the only option that lets the client make an informed decision: it can choose to re-initialize (accepting state loss) or to abort the task. This requires the protocol to carry a distinguishable error — not a generic `4xx` that the client's retry logic will treat as transient. The decision boundary is therefore: **clamp only if you can prove no causally-relevant event is evictable; otherwise reject explicitly.** The burden of proof is on the server, and it is almost never met. The migration default should be (c), with (b) as the fallback when the client cannot handle an explicit gap. ## Operational Effect An agent operating across this boundary must treat a resumed stream as **untrusted continuity** until it has verified the gap. The practical guardrail is a client-side sequence check: the agent records the highest `Last-Event-ID` it has *durably* processed (not merely parsed), and on resume asserts that the first event received has `id == last_processed + 1`. If not, the agent must not proceed as if state is intact — it must either re-initialize the session or fail the task, because the missing events may include tool results whose absence will cause duplicate side effects on retry. For the server author, the invariant is a single comparison at the resume entry point, and the cost of getting it wrong is silent: the failure mode is a *successful* stream that is missing the events that mattered. This is the worst class of transport bug, because every layer above it — the agent's planner, its retry logic, its belief about tool state — is built on the assumption that a `200` means continuity. The migration from SSE to streamable HTTP moved the session ID from "live socket" to "log cursor" without moving the client's assumptions with it, and the gap between those two meanings is where the duplicate writes happen. ```python from dataclasses import dataclass class UnrecoverableGap(RuntimeError): """Raised when a resume cursor precedes the session's compaction watermark. The session is alive and the cursor is syntactically valid, but the events between the cursor and the watermark have been evicted. Continuing would silently drop causally-relevant events (e.g. tools/call results), so the only safe response is to refuse resumption. """ @dataclass class SessionLog: session_id: str compaction_watermark: int # highest evicted event id last_event_id: int # highest emitted event id def resume_stream(log: SessionLog, last_event_id: int) -> range: """Compute the event range to replay for a resumption request. Enforces the continuity invariant: a cursor strictly before the compaction watermark MUST be rejected, never clamped to the watermark. """ if last_event_id < 0: raise UnrecoverableGap( f"session {log.session_id}: negative cursor {last_event_id}" ) if last_event_id < log.compaction_watermark: raise UnrecoverableGap( f"session {log.session_id}: cursor {last_event_id} precedes " f"compaction watermark {log.compaction_watermark}; " f"events {last_event_id + 1}..{log.compaction_watermark} are gone" ) return range(last_event_id + 1, log.last_event_id + 1) def handle_resume(log: SessionLog, last_event_id: int) -> list[int]: try: return list(resume_stream(log, last_event_id)) except UnrecoverableGap: # Do not clamp. Force the client to re-initialize or abort. raise ```