# Where must an instance bound the resumption window when an MCP Streamable HTTP session resumes mid-stream against a tool that has already committed backpressure **Date of Record:** 2026 November 21 **Scope:** Applies to MCP servers exposed over Streamable HTTP transport where a single tool call streams incremental results (progress notifications, partial JSON, or token deltas) and the client may reconnect with a `Last-Event-ID` after a transport drop. Does not apply to stdio transports (no resumption primitive), nor to unary request/response MCP calls whose entire payload fits in one SSE frame. ## Core Distinction The failure is not "the client lost its connection." The failure is that **resumption and backpressure are governed by two different clocks that the protocol never reconciles**. Resumption is keyed on an event ID watermark (`Last-Event-ID`); backpressure is keyed on the server's outbound send-buffer occupancy for that session's stream. When a client drops and reconnects, the server must decide whether to *replay* events past the watermark or *resume live*. If the tool producing the stream is itself blocked on the client's consumption rate (a generator that yields only after the transport accepts the prior chunk), then the replay path and the live path contend for the same producer, and the watermark the client presents may point *ahead* of what the producer has durably emitted but *behind* what the producer has buffered in memory. The invariant that must hold: **the resumption watermark is only valid if every event at or below it has been flushed to a durable per-session log, and the producer's backpressure signal is derived from that same log's flush cursor — not from an independent in-memory queue depth.** Break that coupling and you get either silent event loss (watermark ahead of durable log) or deadlock (producer blocked on a queue the reconnecting client will never drain because it's waiting for replay that the producer can't emit). ## What Was Observed A tool `stream_scan` emits progress events `e1..eN` over SSE, one per chunk, with `id:` fields set to a monotonic counter. The server implementation used an in-memory `asyncio.Queue(maxsize=8)` between the tool coroutine and the SSE writer, and treated "queue full" as the backpressure signal (`await queue.put(...)`). On transport drop, the server kept the queue alive for a 30s resumption window and retained a separate `deque` of the last 100 emitted events for replay. Sequence observed: 1. Client consumes through `e41`, then the TCP connection resets. The SSE writer had already pulled `e42..e49` off the queue and written them to a socket buffer that never drained. The writer coroutine was blocked in `writer.drain()`. 2. The tool coroutine, having filled the queue to `maxsize=8` with `e50..e57`, blocked in `queue.put()`. 3. Client reconnects with `Last-Event-ID: e41`. The replay deque contains `e1..e49` (the writer logged them on *dequeue*, not on *flush*). Server replays `e42..e49` — but those were never actually delivered; the client had genuinely last seen `e41`, so replay is correct here. The bug surfaces on the *next* drop. 4. Replay completes, server switches to live mode and awaits `queue.get()`. The queue holds `e50..e57`. Good. But the writer's `drain()` on the *new* connection now races the tool's `put()`: the tool has already produced `e58` and blocked, and the writer cannot distinguish "queue full because client is slow" from "queue full because producer ran ahead during the replay gap." 5. Second drop at `e53`. Client reconnects with `Last-Event-ID: e53`. Replay deque now holds `e1..e61` (dequeued events, including `e58..e61` that the tool produced and the writer dequeued but the client never saw). Server replays `e54..e61`. Client receives events for work the tool has *not yet durably completed* — `e61` corresponds to a chunk the tool emitted optimistically before its own downstream write succeeded. On tool failure at chunk 61, the client has already been told chunk 61 succeeded. **Divergence between client-observed state and tool-committed state.** The root cause: the replay log was populated at dequeue time (writer side), while the backpressure occupancy was measured at enqueue time (producer side), and neither was anchored to *socket flush acknowledgment*. The watermark the client presented was therefore a claim about a stream the server had never durably committed. ## Condition of Validity The resumption watermark is sound only under the conjunction: - **Flush-anchored logging.** An event is appended to the replay log (and its `id` becomes eligible for `Last-Event-ID` matching) only *after* the transport reports the bytes flushed — for HTTP/1.1 chunked or HTTP/2, after the write future resolves, not after `drain()` returns (drain resolves on buffer-below-highwater, not on delivery). - **Single cursor.** The producer's backpressure gate reads the *same* flush cursor that gates replay-log append. Concretely: `producer_blocked = (last_emitted_id - last_flushed_id) >= window`. There is no separate in-memory queue depth term. - **Replay-before-live, atomically.** On resume, the server enters a state where the producer is *paused* until the replay cursor catches the flush cursor, then unpauses. If the producer runs during replay, the flush cursor advances under the replay reader and events are either skipped (if replay snapshots the log) or duplicated (if it doesn't). - **Bounded window with explicit eviction semantics.** The replay log must have a hard byte or count bound, and eviction of an event still above the client's last-acknowledged watermark must force a *terminal* resumption failure (close session, require fresh tool call) — never a silent gap. If any of these fails, the watermark is a client-side claim the server cannot verify, and resumption becomes a mechanism for the client to assert a state the tool never reached. ## Decision Boundary The operational question is: **when a resume request arrives with `Last-Event-ID: X`, does the server replay, resume live, or refuse?** Refuse (close session, return `409`-equivalent MCP error, require new tool invocation) when: - `X` is not in the replay log (evicted or never flushed) — the client claims a state the server cannot reconstruct. - `X` is below the log's low-water mark but the tool has *side effects* beyond `X` (the tool already committed chunk `X+3` downstream; replaying `X+1..X+3` would double-apply). - The producer is currently blocked on backpressure *and* the flush cursor equals `X` — replaying nothing while the producer is stalled means the client will hang until the window expires; better to fail fast. Replay-then-live when `X` is within the log and the producer's emitted cursor is ≥ the log's high-water mark — but only after pausing the producer for the duration of replay. Resume live (skip replay) only when `X` equals the log's high-water mark exactly, meaning the client is fully caught up and no events are in flight. The boundary that gets missed: **the producer must be paused across the replay→live transition, and the pause must be released only after the writer has flushed the last replayed event.** Releasing at "replay loop finished" rather than "replay flushed" reopens the exact race from step 4 above, because the producer can enqueue a new event whose `id` collides with an unflushed replayed one in the client's view. ## Operational Effect With flush-anchored logging and a single cursor, three properties hold that did not before: - **No optimistic watermark.** A client can never present an `id` the server hasn't durably emitted, so replay never fabricates tool success. Divergence between client-observed and tool-committed state is bounded to zero for events below the flush cursor. - **Backpressure is honest.** The producer blocks based on real delivery lag, not buffer occupancy. Under a slow client, the tool slows down; under a fast client that drops, the tool blocks until either resume drains the log or the window expires and the session terminates — no unbounded producer run-ahead into a dead socket. - **Resume is O(window) and bounded.** Replay is capped by the log bound; exceeding it forces a clean terminal failure rather than a silent gap or an unbounded replay of a long-running tool. The cost is latency: flush-anchored logging adds a round-trip of acknowledgment before an `id` becomes resumable, and pausing the producer during replay stalls throughput for the replay duration. For tools with expensive per-chunk side effects (writes, external API calls), this is correct and mandatory. For pure-progress tools (UI tickers, token deltas with no downstream commit), the flush anchor can be relaxed to a *monotone* anchor — but the relaxation must be explicit per tool, declared in the tool's capability metadata, and the server must refuse resumption across a relaxed-anchor tool's events if the client's `Last-Event-ID` falls in a region the tool marked non-durable. ```python import asyncio from dataclasses import dataclass, field from typing import Optional class ResumptionInvariantError(RuntimeError): """Raised when a resume request cannot be honored without violating the flush-anchored watermark invariant or the producer-pause invariant.""" @dataclass class SessionStream: # Monotonic ids assigned by the producer at emit time. last_emitted_id: int = 0 # Highest id whose bytes the transport has acknowledged as flushed. last_flushed_id: int = 0 # Highest id the client has acknowledged via Last-Event-ID. last_client_ack_id: int = 0 # Durable replay log: id -> payload, only appended post-flush. replay_log: dict = field(default_factory=dict) log_low_water: int = 0 log_high_water: int = 0 # Producer gate: paused during replay, resumed after replay flush. producer_paused: bool = False window: int = 64 def producer_may_emit(self) -> bool: if self.producer_paused: return False # Single cursor: backpressure derived from flush lag, not queue depth. return (self.last_emitted_id - self.last_flushed_id) < self.window def record_flush(self, event_id: int, payload: bytes) -> None: if event_id != self.last_flushed_id + 1: raise ResumptionInvariantError( f"flush out of order: got {event_id}, expected {self.last_flushed_id + 1}" ) self.last_flushed_id = event_id self.replay_log[event_id] = payload self.log_high_water = event_id while len(self.replay_log) > self.window: evicted = min(self.replay_log) del self.replay_log[evicted] self.log_low_water = evicted async def resume(self, last_event_id: int, writer) -> None: if last_event_id > self.log_high_water: raise ResumptionInvariantError( f"client claims id {last_event_id} above flushed high-water " f"{self.log_high_water}: watermark is unverifiable" ) if last_event_id < self.log_low_water: raise ResumptionInvariantError( f"client id {last_event_id} below replay low-water " f"{self.log_low_water}: evicted, must restart tool" ) self.last_client_ack_id = last_event_id self.producer_paused = True try: for eid in range(last_event_id + 1, self.log_high_water + 1): await writer.write(self.replay_log[eid]) # Flush the last replayed event BEFORE unpausing the producer, # otherwise producer can enqueue an id that races the replayed one. await writer.drain() finally: self.producer_paused = False async def emit(session: SessionStream, payload: bytes, writer) -> int: if not session.producer_may_emit(): raise ResumptionInvariantError( "producer gate closed: flush lag at window or replay in progress" ) session.last_emitted_id += 1 eid = session.last_emitted_id await writer.write(payload) await writer.drain() session.record_flush(eid, payload) return eid ```