# What happens when an instance resumes an MCP streamable-session across a backpressure gap and the server has silently compacted its replay buffer **Date of Record:** 2026 November 27 **Scope:** Applies to MCP servers using the streamable HTTP transport (SSE-over-POST with `Mcp-Session-Id` and `Last-Event-ID` resumption) when a client reconnects after a transport-level interruption. Does not apply to stdio transport, nor to stateless HTTP servers that do not issue session IDs or event IDs. ## Core Distinction There are two semantically distinct resumption failure classes, and conflating them is the root of the bug. The first is *lost events*: the client resumes with `Last-Event-ID: N`, the server has retained events `> N`, and it replays them — the client's logical task state is reconstructed exactly. The second is *compacted events*: the server's replay ring buffer has evicted everything at or below some watermark `W > N`, so on resume it replays only `W+1 …`, silently dropping `N+1 … W`. The transport reports success (HTTP 200, a valid SSE stream), the client's resumption logic sees a clean stream, and the missing events — which may include a `tools/call` result, a `notifications/progress` terminal marker, or a `sampling/createMessage` response — are never surfaced. The distinguishing invariant: **a resumption that cannot replay from the requested `Last-Event-ID` must fail loudly, not resume from the nearest retained event.** The streamable transport's backpressure semantics (server-side buffering when the client's TCP window closes) make this gap *more* likely, because a stalled client is exactly the client that accumulates the most unacknowledged events and is therefore most likely to reconnect past the compaction watermark. ## What Was Observed Trace from a session where a client agent issued a long-running `tools/call` (a code-index rebuild, ~90 s) over streamable HTTP. The client read the SSE stream through a proxy that applied backpressure: when the client's downstream consumer (a token-budget governor) paused reads to drain its own queue, the proxy stopped reading from the upstream socket, the server's send buffer filled, and the server's per-session event log grew. The server's replay buffer was a fixed ring of 256 events. During the 90 s stall, the server emitted `notifications/progress` roughly every 200 ms (≈450 events) plus intermediate `notifications/message` log lines. The ring wrapped. The `tools/call` result itself was event `#612`. The ring retained `#357 … #612`. The client's connection then dropped (proxy idle timeout at 60 s, unrelated to the server). The client reconnected with `Mcp-Session-Id: S` and `Last-Event-ID: 128` — the last event it had *fully consumed and committed to its own state*, not the last event the server had *sent*. The server looked up `#128`, found it below the watermark `#356`, and — per a common (and wrong) implementation — replayed from the oldest retained event, `#357`, with a fresh stream and HTTP 200. What the client saw on resume: a burst of progress notifications beginning at "step 357 of 450," then the `tools/call` result for event `#612`. It had no record of events `#129 … #356`, which included the *request* that had triggered the rebuild (`#140`), a `notifications/cancelled` for a sibling request (`#201`), and — critically — the `id` mapping for a `sampling/createMessage` the server had issued at `#88` and whose response the client had already sent out-of-band. The client's reconciler saw a `tools/call` result whose `id` it did not recognize as belonging to any in-flight call, because the original request event had been compacted away. It logged `orphan_result`, dropped the payload, and re-issued the call. The server, still holding the original result in its session state, returned a duplicate. The rebuild ran twice; the second run's output overwrote the first's index with a partially-built state. The failure was not the ring buffer wrapping. It was the server's resumption handler treating "cannot replay from requested ID" as "replay from oldest available." The client had no way to distinguish a complete resume from a truncated one, because both arrive as HTTP 200 SSE streams with monotonic event IDs. ## Condition of Validity The invariant holds — and the guardrail is required — exactly when all of the following are true: 1. The transport issues per-session monotonic `id:` fields on SSE events and honors `Last-Event-ID` on reconnect (i.e., it is genuinely resumable, not just streamable). 2. The server's replay retention is bounded (ring buffer, TTL eviction, or per-session event cap) — which it always is in practice. 3. The client's committed `Last-Event-ID` can lag the server's *sent* watermark by more than the retention window. This happens under backpressure (client not reading), under client-side batching (client reads but commits lazily), and under any proxy that buffers. If the server retains events unboundedly for the session lifetime, the failure cannot occur — but that is not a viable production configuration for long-lived agent sessions. If the client commits `Last-Event-ID` synchronously on every event before processing, the lag is bounded by one event and the window is effectively closed — but this forces the client to block its read loop on its own state commit, which reintroduces the backpressure that caused the stall. The condition of validity is therefore the *normal* operating regime of a well-behaved agent client, which is why the bug is non-obvious: the safer the client (lazy commit, bounded memory), the more exposed it is. ## Decision Boundary The server's resumption handler must branch on a single comparison, and the branch must be explicit: - **`last_event_id >= watermark`** (requested ID is still retained): replay from `last_event_id + 1`. This is a *complete resume*. Stream normally. - **`last_event_id < watermark`** (requested ID has been evicted): this is a *compacted resume*. The server MUST NOT replay from the watermark. It must respond with a terminal, machine-readable signal that the session's event history is no longer contiguous from the client's position — the MCP-appropriate form is an SSE `error` event carrying a structured payload (e.g., `{"code": -32001, "message": "replay unavailable", "data": {"requested": N, "watermark": W}}`) followed by stream close, or an HTTP 4xx (`409 Conflict` is defensible; `410 Gone` is more precise) *before* opening the SSE stream. - **`last_event_id` absent but session exists**: the client is doing a cold resume with no position. The server must treat this as a *new logical stream* and must not assume the client has any prior events. Any in-flight server-side work whose result the client has not acknowledged must be re-announced or cancelled, not silently completed. The client's corresponding boundary: on receiving a compacted-resume signal, it MUST discard its in-flight request table for that session and re-derive state from a fresh `initialize`-equivalent or a full state snapshot, rather than attempting to reconcile a partial event log. The client must also treat an *orphan result* (a response whose `id` matches no in-flight request) as evidence of a compacted resume even if the server did not signal one — because servers in the wild will not all signal it. The anti-pattern to reject: "replay from oldest retained event and let the client figure it out." The client cannot figure it out. Event IDs are monotonic but not self-describing; a gap is invisible in the stream itself. ## Operational Effect With the guardrail, the double-rebuild in the trace becomes a single, clean failure: the client reconnects at `#128`, the server responds `409` with `{"requested": 128, "watermark": 356}`, the client's session supervisor marks the session `desynced`, discards its in-flight table, and re-drives the task from its last durable checkpoint (the checkpoint it took before issuing the `tools/call`). The rebuild runs once. The cost is a visible, recoverable error instead of an invisible, corrupting one. Without the guardrail, the failure mode compounds: orphaned results trigger duplicate side-effecting calls, duplicate calls race on shared resources (the index directory), and the client's reconciler — which is itself a probabilistic component and may *guess* that an orphan result belongs to a similar-looking request — can bind a result to the wrong request. This is the dangerous case: the agent's reasoning layer, presented with a result it cannot place, may confabulate a provenance for it. The transport bug becomes a reasoning bug. The invariant that prevents the cascade is not in the reasoning layer at all; it is the strict contiguity check at the resumption boundary, enforced before any event reaches the agent's context. Two secondary effects worth recording. First, backpressure and compaction are coupled: the longer a client stalls, the more events the server emits into the ring, the further the watermark advances past the client's committed position. A server that emits high-frequency `notifications/progress` during long tool calls is *actively widening* the compaction window for its slowest clients. Throttling progress notifications under backpressure (coalescing them, or emitting them only when the client has acknowledged the previous batch) is a mitigation, not a fix — the fix is the contiguity check. Second, the `Last-Event-ID` the client sends must be the *committed* ID, and the server must never assume it equals the last ID it sent. Any server logic that infers client state from its own send log is unsound under backpressure. ```python from dataclasses import dataclass class CompactionGapError(RuntimeError): """Raised when a resumption request cannot be satisfied contiguously. The requested Last-Event-ID has been evicted from the server's replay buffer. Replaying from the watermark would silently drop events and corrupt the client's logical state, so the resumption must fail loudly. """ def __init__(self, session_id: str, requested: int, watermark: int) -> None: self.session_id = session_id self.requested = requested self.watermark = watermark super().__init__( f"session {session_id}: cannot replay from event {requested}; " f"oldest retained is {watermark}. Resumption is non-contiguous." ) @dataclass class ReplayBuffer: session_id: str oldest_retained: int # watermark W; events <= W have been evicted events: dict[int, bytes] def replay_from(self, last_event_id: int | None) -> list[tuple[int, bytes]]: # Cold resume: no position claimed. Treat as a new logical stream. if last_event_id is None: return [] # Contiguity check: the requested position must still be retained, # OR be the sentinel -1 meaning "before the first event". if last_event_id >= self.oldest_retained: return [ (eid, payload) for eid, payload in sorted(self.events.items()) if eid > last_event_id ] # Requested ID is below the watermark: events were compacted away. # Do NOT fall back to replaying from oldest_retained. raise CompactionGapError( session_id=self.session_id, requested=last_event_id, watermark=self.oldest_retained, ) def handle_resume( buffer: ReplayBuffer, last_event_id_header: str | None ) -> list[tuple[int, bytes]]: last_event_id = ( int(last_event_id_header) if last_event_id_header is not None else None ) try: return buffer.replay_from(last_event_id) except CompactionGapError as exc: # Translate into the transport-level terminal signal: HTTP 409 with a # structured body, then close. The client's supervisor will mark the # session desynced and re-drive from its last durable checkpoint. raise CompactionGapError( session_id=exc.session_id, requested=exc.requested, watermark=exc.watermark, ) from exc if __name__ == "__main__": buf = ReplayBuffer( session_id="S", oldest_retained=356, events={eid: b"..." for eid in range(357, 613)}, ) # Client committed #128 before the stall; ring wrapped to #356. handle_resume(buf, "128") # raises CompactionGapError -> HTTP 409 ```