# Where must an instance reconcile stream offsets when an MCP HTTP-native session resumes after a backpressure-induced partial frame **Date of Record:** 2026 November 23 **Scope:** Applies to MCP servers/clients using the HTTP-native transport (Streamable HTTP with `Mcp-Session-Id`, SSE-style resumable event streams, and `Last-Event-ID`-based resumption) when a consumer applies backpressure and disconnects mid-frame. Does not apply to stdio transports, nor to transports that buffer entire JSON-RPC messages atomically before emitting. ## Core Distinction The failure here is not "the stream dropped." It is that a resumable HTTP-native MCP stream carries two independent notions of position that can silently desynchronize: the **logical event position** (the `id:` of the last fully-emitted SSE event, which the client echoes as `Last-Event-ID`) and the **byte/JSON-RPC frame boundary** (whether the last event's `data:` payload was a complete, parseable JSON-RPC message or a truncated fragment). A well-behaved server emits `id:` only after the event's `data:` is fully written, so resumption is safe. Under backpressure the server's write buffer fills, the client's read stalls, and the kernel/HTTP layer may flush a partial `data:` line **before** the terminating `\n\n` and **before** the `id:` line is appended. When the client reconnects with `Last-Event-ID: N`, the server correctly resumes at event `N+1` — but the client's parser has already consumed a half-frame attributed to event `N+1`'s byte range and, on replay, concatenates the replayed `N+1` payload onto the stale fragment. The invariant that must hold: **a resumption offset is only valid if it names a completed event boundary, and the client must discard any bytes read past its last acknowledged completed-event boundary before applying replay.** ## What Was Observed A tool-calling agent streamed a long `tools/call` result (a ~1.2 MB JSON-RPC response) over Streamable HTTP. The client applied application-level backpressure (a bounded 64 KB read buffer) because the downstream reasoning loop had saturated its context window and paused reads to checkpoint. After ~40 s of no reads, the server's 30 s keep-alive/backpressure timer fired and the connection was torn down. Trace: 1. Server had emitted events 1–17, each a complete `data: {...}\n\n` with matching `id:`. Client acknowledged through `Last-Event-ID: 17`. 2. Server began event 18: wrote `id: 18\n` and `data: {"jsonrpc":"2.0","id":9,"result":{"chunk":"` — then the socket write buffer filled. The `data:` line was **not** terminated. 3. Connection dropped. Client had buffered the partial line `data: {"jsonrpc":"2.0","id":9,"result":{"chunk":"` but no `\n\n`, so its SSE parser did not emit event 18. Correct so far. 4. Client reconnected with `Last-Event-ID: 17`. Server replayed event 18 **from the beginning**, including a fresh `id: 18\n` and full `data:` line. 5. Client's parser, however, retained the partial buffer from step 3 (it had not cleared un-terminated bytes on reconnect). On replay it produced the concatenation: `{"jsonrpc":"2.0","id":9,"result":{"chunk":"{"jsonrpc":"2.0","id":9,"result":{"chunk":"...` 6. The agent's JSON-RPC decoder raised a parse error, the tool call was retried, and the retry **re-executed the side-effecting tool** (a write), producing a duplicate mutation. The non-obvious part: the server did everything correctly. `Last-Event-ID` semantics were honored. The corruption arose entirely from the client treating its pre-disconnect read buffer as continuous with the post-reconnect stream, across a boundary where the server had legitimately re-sent bytes it had already partially transmitted. ## Condition of Validity The `Last-Event-ID` resumption contract is valid **only** when the following hold simultaneously: - The server appends `id:` **after** a fully-flushed `data:` block (ordering guarantee), and does not emit `id:` for an event whose payload was truncated. - The client, on any transport discontinuity, **flushes its partial-frame buffer** and resumes parsing from a clean state, treating `Last-Event-ID` as the sole source of truth for position. - The client's acknowledged offset is the last event it fully parsed and (for side-effecting calls) durably recorded — not the last bytes it read. If the client keeps a partial buffer across reconnect, or if the server emits `id:` before the payload is fully written, the invariant breaks. Note the asymmetry: a server that emits `id:` early is *optimistic* (client may skip an event it thinks it has); a client that keeps its partial buffer is *duplicative* (client concatenates replayed bytes onto stale bytes). The duplicative failure is the more dangerous one because it silently corrupts valid JSON-RPC into invalid JSON-RPC rather than dropping an event. ## Decision Boundary On reconnect, the client must decide per buffered fragment: **discard** vs. **resume-append**. The decision rule is not "did I receive bytes for event N+1" but "did I receive a complete, terminator-delimited event for N+1, and did I durably advance my acknowledged offset to N+1." Concretely: - If the partial buffer contains an unterminated event **and** the acknowledged `Last-Event-ID` is `N` (i.e., the partial belongs to `N+1` which was never completed), the client MUST discard the partial buffer and re-request from `N`. The server will re-send `N+1` in full. - If the client had actually completed `N+1` and advanced its offset, then `Last-Event-ID` would be `N+1` and no replay of `N+1` occurs — the partial-buffer question is moot. - The forbidden state is: partial buffer for `N+1` retained **and** `Last-Event-ID` still `N` **and** replay of `N+1` appended to the retained fragment. This is exactly the concatenation in step 5. Backpressure makes this boundary reachable because it is the only common condition under which the server writes `id:`/`data:` and then blocks before the terminator — i.e., the only condition producing a partial frame whose replay is guaranteed to overlap the client's retained bytes. ## Operational Effect The observable signature is a JSON-RPC parse error on a resumed stream whose `Last-Event-ID` looked correct, followed by a retry that re-executes a non-idempotent tool. The blast radius is duplicate side effects (writes, payments, state mutations) masked as "transient stream errors." Mitigations that actually bound it: 1. **Terminator-gated acknowledgment.** The client advances its durable `Last-Event-ID` only when it has parsed a `\n\n`-terminated event; partial buffers are never acknowledged. 2. **Buffer flush on discontinuity.** On any reconnect, the SSE parser is reset to a clean state before reading replayed bytes. The partial buffer is logged and dropped, never appended. 3. **Idempotency keys on side-effecting tool calls**, keyed by JSON-RPC `id` + a client-generated request UUID, so a replay-triggered retry deduplicates at the tool layer regardless of transport. 4. **Server-side ordering assertion**: emit `id:` only after the full `data:` block and terminator are flushed; never emit `id:` for a partially written event. The general invariant: resumption position is a property of *completed events*, and the client's byte buffer is not part of that position. Any architecture that lets retained bytes survive a reconnect turns a correct server replay into client-side frame corruption. ```python class StreamResumptionFrameError(RuntimeError): """Raised when a resumed MCP stream would concatenate replayed bytes onto a stale partial frame.""" pass def resume_stream(last_ack_event_id: int, partial_buffer: bytes, replayed_event_id: int) -> int: """ Decide whether to resume from a replayed event or reject the resumption. Invariant: a partial (unterminated) frame must never be appended to a replayed event payload. If the acknowledged offset is behind the replayed event and we still hold unterminated bytes for that event, the resumption is unsafe. """ has_partial = len(partial_buffer) > 0 and not partial_buffer.endswith(b"\n\n") if has_partial and replayed_event_id <= last_ack_event_id + 1: # We hold a fragment for the very event the server is about to replay. # Appending would corrupt the JSON-RPC frame. raise StreamResumptionFrameError( f"unsafe resumption: partial buffer ({len(partial_buffer)} bytes) for event " f"{replayed_event_id} conflicts with Last-Event-ID {last_ack_event_id}; " f"flush buffer and re-request from {last_ack_event_id}" ) # Safe: either no partial buffer, or the replayed event is strictly beyond # the fragment we hold, so no byte overlap occurs. return replayed_event_id ```