# How does an instance detect a split-brain SSE stream when an MCP session resumes on a second HTTP node mid-tool-call **Date of Record:** 2026 December 2 **Scope:** Applies to MCP servers using the HTTP-native streamable transport (Streamable HTTP, `text/event-stream` responses with `Mcp-Session-Id` and `Last-Event-ID` resumption) where session state may migrate across load-balanced nodes. Does not apply to stdio transport, nor to single-node deployments where session affinity is guaranteed by the process boundary. ## Core Distinction There are two categorically different meanings of "resume" in MCP Streamable HTTP, and conflating them produces a silent correctness failure: 1. **Event replay resume** — the client reconnects with `Last-Event-ID: N` and the server replays buffered SSE events from `N+1`. This is a *transport* guarantee about the byte stream. 2. **Session state resume** — the server rebinds `Mcp-Session-Id` to the same logical agent context (in-flight tool call, pending `sampling/` or `roots/` state, negotiated capabilities). This is a *state* guarantee about the execution. The MCP spec defines (1) explicitly via `Last-Event-ID` and requires servers to support it *if* they advertise resumability. It does **not** require (2) across nodes. A well-meaning deployment that puts an MCP server behind a round-robin HTTP load balancer with a shared session store often implements (1) on each node independently while failing (2) — the new node replays the event stream from its own (or a shared) buffer, the client believes it is continuing the same logical turn, but the tool invocation that was mid-flight on node A is still running there, unwatched, while node B has no record of it. The client sees a coherent token stream. The system has split-brained. The non-obvious part: **there is no protocol-level signal that distinguishes "resumed correctly" from "resumed onto a node that has the event buffer but not the execution."** Both cases produce a valid `text/event-stream` with a valid `id:` sequence. The invariant that must be defended is not "did we reconnect" but "is the *executor identity* of the in-flight tool call the same as the *session identity* the client believes it is talking to." ## What Was Observed A multi-step agent invoked a long-running MCP tool (`run_migration_plan`, ~90s of wall time, streaming progress events). The client's HTTP connection to node A dropped at t≈40s (a routine LB idle-timeout reset on a NAT boundary, not a server crash). The client reconnected per spec: ``` GET /mcp HTTP/1.1 Mcp-Session-Id: 7f3c2a... Last-Event-ID: 118 ``` The LB routed to node B. Node B's session store held the *event log* for `7f3c2a...` (replicated, cheap) but not the *execution handle* (node-local, a `subprocess` + a `asyncio.Task` running on node A). Node B replayed events 119–131 from the shared buffer — these were the last events flushed to the log before the drop, which happened to include a `progress` notification at 60% and no terminal event. Node B then, per its implementation, treated the absence of a terminal event as "call still in progress" and began emitting *its own* keepalive `progress` events synthesized from the last known progress value, because its `progress` emitter had no backing task and defaulted to holding the last value. Meanwhile node A's task completed at t≈90s, emitted its terminal `result` event into the shared event log (event 132), and released the execution handle. The client never saw event 132, because node B's SSE stream had already passed `Last-Event-ID` 131 and node B does not re-scan the log for events appended after the reconnect — it only replays up to the current tail *at reconnect time*, then streams live events *for its own session binding*, which is empty. The client sat on a stream emitting frozen 60% progress until its own turn timeout, then issued a *new* `tools/call` — because from its perspective the previous one never returned. The tool executed a second time. The migration plan ran twice. The failure is not "connection dropped" (expected) and not "event lost" (spec-permitted if resumability is not advertised). The failure is that **resumption produced a session that was transport-consistent and execution-inconsistent, with no error surfaced at any layer.** ## Condition of Validity The split-brain is only possible when all of the following hold simultaneously. Each is a necessary condition; removing any one bounds the failure: - **C1 — Event log and execution handle are decoupled in durability.** The SSE event buffer is replicated/shared across nodes; the tool execution handle is node-local. This is the default outcome of "just put a shared Redis in front of the event log" and is the single most common root cause. - **C2 — Resumability is advertised** (`Last-Event-ID` honored), so the client is *entitled* to expect replay and does not treat a reconnect as a hard failure requiring idempotency-keyed retry. - **C3 — The resumed stream emits live events with no terminal event in the replay window.** If the replay buffer contained the terminal event, node B would close the stream correctly and the client would see the result. The bug only manifests when the drop occurs *between* the last flushed event and the terminal event — i.e., during the execution tail. - **C4 — The client's turn timeout exceeds the tool's remaining runtime**, so the client waits on the frozen stream rather than timing out and retrying with a dedup key. If the client times out first, it retries and the server's idempotency layer (if any) catches the double-execution. The bug is *masked* by aggressive client timeouts and *exposed* by patient ones — which is why it appears in production on the long-running tools where retry is most expensive. The invariant that fails is: **for a given `Mcp-Session-Id` and `Last-Event-ID`, the node serving the resumed stream must be able to prove it holds (or can reach) the executor that will produce the next event with `id > Last-Event-ID`.** If it cannot, it must not open a live stream; it must either replay-to-terminal-and-close or return an explicit session-migration error. ## Decision Boundary The server, on receiving a resumed `GET /mcp` with `Last-Event-ID: N`, must make a binary decision before writing a single byte to the stream: - **If the replay buffer contains a terminal event for the in-flight call with `id > N`:** replay through the terminal event and close the stream. This is safe on any node, because the execution is already done and the result is durable. - **If the replay buffer's tail is `id == N` (no events beyond the client's cursor) AND this node holds the execution handle for the call:** open the live stream. Safe. - **If the replay buffer's tail is `id == N` AND this node does *not* hold the execution handle:** **do not open a live stream.** The correct responses are (a) `409 Conflict` with a machine-readable `session_migration_required` body carrying the owning node or a resume token, or (b) a `text/event-stream` that replays to the current tail and then closes with no live phase. Synthesizing keepalives or holding the connection open is the failure. - **If the replay buffer's tail is `id > N` but contains no terminal event** (events were appended by a *different* node's execution): this is the ambiguous case. The node must consult the session store for the executor's liveness (heartbeat/lease), not assume. If the lease is live and owned elsewhere, redirect. If the lease is expired, the call is orphaned; emit a terminal `error` event with `id = tail+1` and close, so the client's turn resolves deterministically rather than hanging. The boundary is *not* "did the reconnect succeed" but "can this node produce the next event, or must it defer." The default LB behavior — route anywhere, answer locally — violates this boundary on every reconnect that lands on a non-owner during the execution tail. ## Operational Effect Concretely, the unguarded system exhibits: - **Silent double-execution** of non-idempotent tools (the migration ran twice). No error at the MCP layer; the client's second `tools/call` is a fresh request with a fresh call id, so server-side dedup keyed on call id does not catch it. - **Frozen progress streams** that pass liveness checks (bytes flow, keepalives arrive) but carry stale state, defeating client-side "is the agent alive" heuristics. - **Orphaned executors** on node A that complete and write to the shared event log with no reader, leaking the result and (if the tool has side effects) applying them without the client ever acknowledging. - **Non-deterministic blast radius**: the bug fires only when the drop lands in the execution tail (C3) on a non-owner node (C1), so it correlates with tool duration and LB topology rather than with any request property — making it nearly invisible in short-tool test suites and near-certain in long-tool production paths under load. The guardrail is a **session-executor lease**: the owning node holds a renewable lease on the `Mcp-Session-Id`; the session store records `{session_id, owner_node, lease_expiry, last_event_id}`; any node serving a resumed stream must verify `owner_node == self` OR `lease_expiry < now` (orphaned) before opening a live stream, and must return `409 session_migration_required` otherwise. This makes the C1 decoupling explicit and forces the non-owner to defer rather than synthesize. ```python import time from dataclasses import dataclass from typing import Optional class SessionMigrationConflict(RuntimeError): """Raised when a resumed SSE stream cannot be served by this node because the in-flight execution is owned elsewhere and still live.""" @dataclass class SessionLease: session_id: str owner_node: str lease_expiry: float # monotonic seconds last_event_id: int has_terminal_event: bool def open_resumed_stream( self_node: str, session_id: str, last_event_id: int, lease: Optional[SessionLease], replay_tail: int, now: Optional[float] = None, ) -> str: """Decide whether this node may open a live SSE stream for a resumed MCP session, or must defer. Returns a mode string; raises on the split-brain boundary rather than synthesizing keepalives. """ now = time.monotonic() if now is None else now if lease is None: # No lease record at all: session unknown to the store. raise SessionMigrationConflict( f"no lease for session {session_id}; refusing live stream" ) # Case 1: terminal event already durable past the client's cursor. if lease.has_terminal_event and replay_tail > last_event_id: return "replay_to_terminal_and_close" # Case 2: this node owns the live execution. if lease.owner_node == self_node and lease.lease_expiry >= now: return "live_stream" # Case 3: another node owns a live execution. Do NOT open a stream. if lease.owner_node != self_node and lease.lease_expiry >= now: raise SessionMigrationConflict( f"session {session_id} owned by {lease.owner_node} " f"(lease live until {lease.lease_expiry:.3f}); " f"client cursor {last_event_id}, replay tail {replay_tail}" ) # Case 4: lease expired -> orphaned execution. Emit a terminal # error event so the client's turn resolves deterministically. return "emit_orphan_terminal_error" ```