# What structural signals indicate that an MCP streamable-HTTP session has silently forked: resumption replay divergence at the `Last-Event-ID` boundary **Date of Record:** 2026 November 25 **Scope:** Applies to MCP servers/clients using the streamable HTTP transport with `Mcp-Session-Id` headers and SSE event resumption via `Last-Event-ID`. Does not apply to stdio transports, single-shot request/response JSON mode, or WebSocket-based MCP bindings where the connection itself is the session. ## Core Distinction The failure is not "the stream dropped." A dropped SSE stream is a normal, expected condition — the client reconnects, sends `Last-Event-ID`, and the server replays events after that ID. The non-obvious boundary is different: **the session has forked into two live server-side continuations that both believe they own the same `Mcp-Session-Id`, and the client's `Last-Event-ID` resumption lands on the wrong one.** This happens because streamable HTTP resumption is defined over an *event ID watermark*, not over a session generation. When a client's TCP connection dies mid-stream, the server may not immediately observe the death (no FIN, half-open socket, proxy that buffers). The client, having given up after its own timeout, reconnects with `Last-Event-ID: N`. If the server has not yet reaped the prior stream handler, it now has two handlers draining the same session's event log. The replay from `N+1` is correct on paper — but the *original* handler is still emitting into a dead socket while the *new* handler emits the same logical events into the live one. Any server-side state mutation keyed to "events delivered" (tool-call deduplication counters, sampling request IDs, progress-token registries) now advances twice, or advances once on a stream nobody reads. The invariant that is being violated: **a session ID must map to at most one active delivery cursor per direction.** Streamable HTTP as commonly implemented enforces this for *creation* (409 on duplicate `initialize`) but not for *resumption*, because resumption is treated as idempotent read-only replay. It is not read-only when the server uses delivery as a side effect. ## What Was Observed A weather-orchestration agent (`tool: get_forecast`, long-running, emits `progress` notifications every 2s) behind an ALB with a 60s idle timeout, client-side read timeout of 30s. Trace: 1. `t=0` — Client POSTs `initialize`, receives `Mcp-Session-Id: S1`. SSE stream opens, first event `id: 1`. 2. `t=28` — Server emits `id: 47` (progress 14/20). Client's read loop is healthy. 3. `t=31` — ALB silently drops the connection (idle timer misfire on a keep-alive race). Client sees EOF, not RST. Client records `Last-Event-ID: 47`. 4. `t=31.4` — Client reconnects: `GET /mcp` with `Mcp-Session-Id: S1`, `Last-Event-ID: 47`. 5. `t=31.4` — Server's session registry still holds stream handler `H_old` for `S1` (reaper runs every 90s; last sweep at `t=0`). Server spawns `H_new`, replays `48..50`, then continues live. 6. `t=32` — `H_old` attempts to write `id: 48` to the dead socket. Write fails silently (kernel buffer accepts, TCP retransmits into the void). Server's `on_delivery` hook for `48` fires anyway, incrementing the tool-call's `delivered_count` and marking progress token `p_14` as acknowledged. 7. `t=34` — `H_new` emits `id: 51` (progress 15/20). Client acks. Server's dedup layer sees `p_15` already advanced by `H_old`'s phantom delivery of `48`→`p_14` and **drops `51` as duplicate** (off-by-one in the token index because `H_old` consumed a slot). 8. `t=60` — Tool completes. Client never received progress 15; its local progress bar stalls at 14/20 but receives the final result. The agent's planner, which gates on "progress ≥ 18 before committing to a second tool call," never commits — it waits, times out at its own 120s budget, and reports partial failure. The structural signal that something forked was **not** the disconnect. It was step 7: a *gap* in delivered event IDs (`51` missing) coinciding with a *contiguous* server-side delivery log. The client's `Last-Event-ID` was monotonically advancing while the server's `delivered_count` was advancing faster than the client's received count — a divergence between two counters that should be locked. ## Condition of Validity This boundary only bites when all of the following hold simultaneously: - The server treats event delivery as a **side-effecting operation** (dedup counters, progress-token registries, sampling-request bookkeeping, at-most-once tool invocation keyed to notification delivery). - The transport is streamable HTTP with `Last-Event-ID` resumption, and the server's stream reaper interval exceeds the client's reconnect latency (common: reaper 60–120s, client reconnect 1–5s). - The client's disconnect is *silent* from the server's perspective (proxy drop, half-open TCP, load-balancer idle timeout) rather than a clean FIN that the handler observes and self-terminates on. - The server does not key replay events to a **stream generation** (a per-connection nonce) in addition to the monotonic event ID. It does **not** bite when: the server is stateless per-request (no delivery side effects), the client uses a fresh session on reconnect (loses `Last-Event-ID` but avoids the fork), or the transport closes the old handler synchronously on new-stream admission for the same session (explicit `H_old.kill()` before `H_new` spawns). ## Decision Boundary The architectural guardrail is a **single-writer admission rule on resumption**, enforced at the session registry, not the event log: - On any `GET /mcp` carrying `Mcp-Session-Id: S` and `Last-Event-ID: N`, the server MUST atomically (a) mark `H_old` for `S` as `superseded`, (b) block until `H_old`'s delivery hook is quiesced or its pending writes are drained-and-discarded, and (c) only then spawn `H_new` with replay from `N+1`. - The delivery hook MUST check a `stream_generation` token before mutating any dedup/progress state; a write from a superseded generation is a no-op on state, even if the socket write "succeeds." - The client MUST treat a **gap in event IDs** concurrent with a healthy stream as a resumption fork signal and re-issue the resume with the last *contiguously received* ID, not the last *seen* ID — because the seen-but-unacked event may have been consumed by the phantom handler. The decision boundary for the agent: **do not gate planning on progress-notification completeness unless the transport provides a contiguous-delivery guarantee.** If it does not, treat progress as advisory and gate on the terminal result only. The cost of gating on advisory signals is exactly the stall in step 8. ## Operational Effect Without the single-writer admission rule, the observable symptoms are: (1) progress notifications with silent gaps that the client cannot distinguish from lossy transport, (2) tool-call dedup counters that over-count, causing legitimate retries to be suppressed as duplicates, (3) sampling requests that are issued twice because the server's "already sampled" flag was set by a phantom delivery, and (4) agent planners that stall waiting for a monotonic signal that has already been corrupted. All four present identically to "the stream was just flaky," which is why the fork goes undiagnosed — the *structural* tell is the counter divergence between client-received and server-delivered, not any single dropped event. The invariant to record: **resumption is a state transition, not a read.** Any transport that models `Last-Event-ID` replay as idempotent read while the server attaches delivery side effects has an unguarded fork window exactly as wide as its stream-reaper interval. ```python class StreamForkDetected(RuntimeError): """Raised when a session's delivery cursor diverges from its replay watermark, indicating two live stream handlers for one Mcp-Session-Id.""" pass class SessionRegistry: def __init__(self, reaper_interval_s: float = 90.0): self.reaper_interval_s = reaper_interval_s self._handlers: dict[str, dict] = {} # session_id -> {generation, delivered, superseded} def admit_resumption(self, session_id: str, last_event_id: int) -> int: """Atomically supersede the prior handler before spawning a new one. Returns the new stream generation. Raises if the prior handler cannot be quiesced within the reaper window (fork would be unguarded).""" prior = self._handlers.get(session_id) if prior is not None: if prior["delivered"] > last_event_id: # Server delivered events the client never acked: phantom handler # advanced past the client's watermark. This is the fork tell. raise StreamForkDetected( f"session {session_id}: server delivered={prior['delivered']} " f"> client last_event_id={last_event_id}; " f"prior generation {prior['generation']} still live" ) if not self._quiesce(prior, timeout_s=self.reaper_interval_s): raise StreamForkDetected( f"session {session_id}: prior handler {prior['generation']} " f"failed to quiesce within {self.reaper_interval_s}s; " f"refusing to spawn concurrent stream" ) new_gen = (prior["generation"] + 1) if prior else 1 self._handlers[session_id] = { "generation": new_gen, "delivered": last_event_id, "superseded": False, } return new_gen def on_delivery(self, session_id: str, generation: int, event_id: int) -> None: """Delivery hook. Must be a no-op on state for superseded generations.""" h = self._handlers.get(session_id) if h is None or h["generation"] != generation: return # phantom write from a dead stream: discard, do not mutate state h["delivered"] = max(h["delivered"], event_id) def _quiesce(self, handler: dict, timeout_s: float) -> bool: # In production: join the handler's write loop, drain its socket buffer, # and mark superseded before returning True. Stub for the record. handler["superseded"] = True return True ```