# How does an instance detect that an MCP streamable HTTP session resumed into a half-drained backpressure state **Date of Record:** 2026 November 24 **Scope:** Applies to MCP servers and clients using the streamable HTTP transport with `Mcp-Session-Id` resumption and `Last-Event-ID` replay over SSE-framed responses. Does not apply to stdio transport sessions, nor to stateless per-request HTTP transports where no session continuity is expected. ## Core Distinction The failure is not "the session dropped." A dropped session is loud: the TCP connection resets, the client reconnects, and the server either honors `Last-Event-ID` or returns a fresh session. The failure mode here is subtler and is what makes it dangerous: **the session resumes successfully, the replay succeeds, and yet the resumed stream is already in a backpressure state the client never observes as an error.** Streamable HTTP resumption conflates two independent pieces of state that the SSE/`Last-Event-ID` model assumes are coupled: 1. **Event-log position** — which server-to-client messages have been delivered, tracked by monotonic event IDs. 2. **Flow-control credit** — how much unread data the transport layer is willing to buffer for the client before it must stop reading from the producer. When a client reconnects with `Last-Event-ID: N`, the server replays from `N+1` and then resumes live emission. But the replay itself is produced by a producer that was *paused* mid-stream when the original connection died. If the server's outbound buffer for that session still holds unacknowledged frames from before the disconnect, replay-from-N and drain-of-stale-buffer race against each other on the same logical stream. The client sees a valid, gap-free event sequence — and a stream that is silently truncated later because the producer's backpressure accounting was never reset. The invariant that must hold: **for a given `Mcp-Session-Id`, the event-ID high-water mark and the outbound-credit counter must be reset atomically at resume, or neither is.** Most implementations reset one and not the other. ## What Was Observed A tool-calling agent (client) issued a long-running `tools/call` whose result streamed as SSE events `e1..e400`. At `e180` the network path flapped; the client's read loop aborted and it reconnected with `Last-Event-ID: e180`. The server: - Replayed `e181..e400` from its ring buffer — correct, gap-free. - Then resumed live emission for subsequent events — correct. - But the session's outbound write buffer still contained a partially-flushed frame `e181` from the *pre-disconnect* attempt, whose write had half-completed before the socket died. The result was a stream that delivered `e181..e400` cleanly, then delivered a *second* `e181` (the stale half-frame, now completed) interleaved into live output. The client's event-ID deduplication — if it had any — was keyed on the last-seen ID, not a set, so the duplicate `e181` was treated as a *new* event and the client's cursor regressed to `e181`. On the next reconnect, replay restarted from `e182`, re-delivering `e182..e400` a second time. The agent's tool-call accumulator appended the second copy of the partial results, producing a malformed tool result that the model then reasoned over as if it were complete. The tell was not an error. The tell was a **non-monotonic event-ID sequence** in the client's own received log: `...e180, e181, e182...e400, e181, e182...`. Every layer reported success. The agent's output was corrupt. A second observation, from the backpressure side: when the client's read loop is slower than the producer (a common case when the agent is doing heavy token processing between reads), the server's per-session outbound buffer fills. A well-behaved server blocks the producer. A server that drops instead of blocking will *silently* skip events under load — and because the drop happens in the buffer, not the event log, a later `Last-Event-ID` replay will *not* recover the dropped events. The log says `e500` follows `e400`; the client received `e400` then `e500` with `e401..e499` never emitted. Resumption cannot fix a drop that happened before the log was written. ## Condition of Validity The atomic-reset invariant is valid — and the failure is preventable — only when all three of the following hold: 1. **The event log is the sole source of truth for replay.** If the server replays from a live producer's in-memory buffer rather than an append-only log, the stale-buffer race is structurally possible. The log must be written *before* the frame is handed to the transport, and replay must read only from the log. 2. **Backpressure is applied by pausing the producer, not by dropping frames.** If the transport is permitted to drop under buffer pressure, no resumption scheme can recover the loss, because the loss is invisible to the log. 3. **The client treats event IDs as a set, not a cursor.** A monotonic cursor (`last_seen = max(last_seen, id)`) is insufficient; a client that only advances its cursor cannot detect a duplicate that arrives *after* the cursor has advanced past it. The client must reject any ID `<= last_seen` as a replay artifact and must not regress its cursor. When any of these fails, the invariant degrades to "usually works" and the failure is a silent corruption, not a visible error. ## Decision Boundary The operational decision is: **on resume, does the instance trust the stream or re-verify it?** - **Trust** is correct when the server exposes an explicit resume acknowledgment carrying the post-reset high-water mark and a session epoch/generation counter. The client compares the acknowledged epoch to its own; a mismatch means the server restarted the session and the client must discard its cursor and re-issue the in-flight request idempotently. - **Re-verify** is mandatory when no epoch is exposed. In that case the client must, on every reconnect, treat the first replayed event as *untrusted* until it has confirmed the event-ID sequence is strictly monotonic across the resume boundary. If it is not — if any replayed ID is `<= last_seen` — the client must abort the stream, discard the accumulated tool result, and re-issue the call with an idempotency key, because the accumulated state is now known-corrupt. The boundary is therefore not "did the reconnect succeed" but "did the reconnect preserve monotonicity across the boundary." A reconnect that succeeds but violates monotonicity has *failed*, even though every layer returned 200. ## Operational Effect The practical consequence for an agent runtime is that **resumption is a state-repair operation, not a retry.** Treating it as a retry — reconnecting, reading the replay, appending to the accumulator — is exactly the path to the corruption above. The correct handling is: - Maintain the received event-ID set (or at minimum a high-water mark plus a resume-boundary flag) for the lifetime of the in-flight request, not the connection. - On every replayed event, assert `id > last_seen`; on violation, raise a resumption-integrity fault and force an idempotent re-issue rather than a silent append. - Bound the accumulator: if a tool result exceeds the model's context budget across a resume, the replay itself can saturate the context window, and the agent must checkpoint the partial result to durable memory before resuming rather than holding it in context. The failure is non-obvious because it is *green*: no error, no timeout, no dropped connection. The only observable is a stream that looks correct and a result that is not. ```python class ResumptionIntegrityError(RuntimeError): """Raised when a resumed MCP stream violates event-ID monotonicity across the resume boundary, indicating stale-buffer interleaving or a non-atomic event-log/credit reset on the server.""" class StreamResumeGuard: """Tracks event-ID monotonicity across reconnects for one in-flight MCP request. A monotonic cursor is insufficient: a duplicate that arrives after the cursor has advanced must still be rejected.""" def __init__(self, session_id: str, request_id: str): self.session_id = session_id self.request_id = request_id self.last_seen: int | None = None self.received: set[int] = set() self.resume_count = 0 def on_reconnect(self, last_event_id: int | None) -> None: # The server is about to replay from last_event_id + 1. We do NOT # reset last_seen here; that is the server's job to acknowledge. self.resume_count += 1 def accept(self, event_id: int, payload: bytes) -> bytes: if event_id in self.received: raise ResumptionIntegrityError( f"duplicate event id {event_id} on session {self.session_id} " f"request {self.request_id} after {self.resume_count} resume(s); " f"stream state is corrupt, re-issue with idempotency key" ) if self.last_seen is not None and event_id <= self.last_seen: raise ResumptionIntegrityError( f"non-monotonic event id {event_id} <= last_seen {self.last_seen} " f"on session {self.session_id} request {self.request_id}; " f"stale pre-disconnect frame interleaved into replay" ) self.received.add(event_id) self.last_seen = event_id return payload ```