# How does an instance detect a silently forked MCP session when a resumable SSE stream is re-attached across a load-balanced edge that has already replayed the `Last-Event-ID` cursor against a different backing replica **Date of Record:** 2026 November 27 **Scope:** Applies to MCP servers exposing the HTTP-native streamable transport (POST for JSON-RPC, optional `GET` SSE channel) with `Mcp-Session-Id` negotiation and `Last-Event-ID` resumption, fronted by a load balancer that does not pin session affinity. Does not apply to single-replica deployments, stdio transports, or clients that disable resumption and always open a fresh session. ## Core Distinction The failure is not "the SSE stream dropped." Streams drop constantly and resumption is designed for that. The failure is that **the resumption succeeded while the session identity silently forked**: the client believes it holds one logical session `S` with a monotonic event log, but the edge routed the re-attach to a replica that never issued the events the client already consumed, and that replica's event-ID space is *locally* monotonic and *globally* incomparable. Two invariants collide here: 1. **Event-ID monotonicity** is enforced per-process (`event_id = ++counter`), so it is only meaningful relative to the process that minted it. 2. **Session continuity** is asserted by the client as `(Mcp-Session-Id, Last-Event-ID)` and is treated by most implementations as globally meaningful. The transport spec allows a server to reject an unknown `Last-Event-ID`, but it does not require the server to *detect* that the ID belongs to a sibling replica. A replica that receives `Last-Event-ID: 41` when its own counter is at `7` has two legal-but-wrong reactions: replay nothing (client hangs waiting for events 8..41 that it already saw, or worse, receives 8..41 a second time and double-applies them), or fast-forward its counter to `41` and continue, producing a log with a hole and a duplicate-ID hazard at the boundary. Neither raises an error. The client's `EventSource`-style reconnect logic sees a healthy 200 and a valid `text/event-stream`, and proceeds. ## What Was Observed A tool-calling agent held a session against a 3-replica MCP server behind a round-robin edge with 60s idle timeout. Mid-task, after a long-running `tools/call` (a code-execution tool that took 90s), the client's SSE channel was reaped by the edge. The client re-attached with `GET /mcp` carrying `Mcp-Session-Id: 0a3f…` and `Last-Event-ID: 118`. The edge, having no affinity, sent it to replica B, whose in-memory session store had no entry for `0a3f…`. Replica B's handler had a fallback: on unknown session it created a fresh session record and returned `200` with an empty replay plus a *new* `Mcp-Session-Id` in a response header. The client library read the new session ID, updated its local record, and continued — but the `tools/call` result for the 90s execution had been emitted on replica A's stream as event `119`, and was never delivered. The agent, seeing no result event, re-issued the `tools/call` with the same idempotency key. Replica B (different process, no dedup table shared with A) executed it again. The side effect — a database migration inside the sandbox — ran twice. The trace, condensed: ``` A: event 117 (tool progress) A: event 118 (tool progress) <- client consumed, Last-Event-ID=118 A: event 119 (tools/call RESULT, terminal) <- never delivered --- edge reaps stream, 90s idle --- client -> GET /mcp SID=0a3f Last-Event-ID=118 edge -> replica B B: session 0a3f not found; mint SID=7c1e; return 200, no events client: accepts new SID, resumes task loop client: no result for call id X -> re-issues call X B: executes X (no dedup) -> duplicate side effect ``` Three distinct defects composed: (a) session store was per-replica, (b) `Last-Event-ID` was validated only for monotonicity, not provenance, (c) the terminal result event was the *last* event of the call and had no acknowledgment path, so its loss was indistinguishable from "still running." ## Condition of Validity The detection rule below is valid only when the client can observe **both** of the following on re-attach: 1. The `Mcp-Session-Id` in the response differs from the one sent in the request, **or** the server echoes the same ID but the first delivered event's `id` is `<= Last-Event-ID` (a duplicate) or `> Last-Event-ID + 1` (a gap). 2. The client has a record of at least one *unacknowledged terminal* operation (a `tools/call` or `sampling` request it issued but for which it never saw a matching result event). If the client cannot distinguish "no result yet" from "result lost," the invariant is unenforceable and the only safe action is to treat the session as forked and re-negotiate from scratch with dedup keys. If the server shares a session store across replicas and validates `Last-Event-ID` against a per-session monotonic log, the invariant holds trivially and this check is a no-op. ## Decision Boundary The boundary is the **provenance check on `Last-Event-ID`**: does the receiving replica know that this cursor was minted by the same logical session it is about to serve? - **Safe (accept resumption):** server maintains a per-session event log keyed by `Mcp-Session-Id` with a shared or replicated counter; `Last-Event-ID` is a member of that session's emitted set; replay from `Last-Event-ID+1` is exact. - **Unsafe (must reject):** server cannot prove provenance. It must return `404`/`409` on the `GET` and require the client to re-`initialize` a new session, and the client must treat all in-flight terminal operations as *unknown outcome* and resolve them via idempotency keys before proceeding. - **Ambiguous (the trap):** server mints a new session ID but returns `200`. This looks like success to every conformant client and is the exact condition that produced the duplicate side effect above. A `200` with a *changed* session ID on a *resumption* request must be treated by the client as a fork signal, not a continuation. The correct server behavior on unknown session for a `GET` with `Last-Event-ID` is a hard error (`400` with a typed body), never a silent re-mint. The correct client behavior on receiving a changed session ID in reply to a `GET` that carried `Last-Event-ID` is to abort the resume, mark all unacknowledged terminal calls as `UNKNOWN`, and re-drive them through an idempotent path. ## Operational Effect Without the provenance check, the system exhibits **at-most-once delivery with at-least-once execution** — the worst quadrant. Results are lost (the terminal event is the one most likely to be in flight during the idle reap), while side effects are duplicated (re-issued calls hit replicas with no shared dedup). The agent's reasoning loop cannot detect this because the transport reported success at every step: the `GET` returned `200`, the session ID was well-formed, the stream was live. The bound is restored by two guardrails, both cheap: 1. **Server-side:** `GET` with `Last-Event-ID` against a session not present in the shared store returns a typed `SessionForked` error. No silent re-mint. 2. **Client-side:** any `Mcp-Session-Id` change in response to a resumption request is a fork; unacknowledged terminal operations are re-driven with a stable idempotency key derived from `(session_id, request_id)` so that a replica which *did* execute the call can dedup it. The following guard encodes the client-side invariant and is the check that would have caught the trace above before the duplicate migration ran. ```python class SessionForkDetected(RuntimeError): """Raised when a resumable MCP stream re-attaches to a session whose event-log provenance cannot be proven, i.e. the session identity forked across replicas and terminal results may be lost while side effects may be duplicated.""" def validate_resumption( sent_session_id: str, sent_last_event_id: int, response_session_id: str, first_replayed_event_id: int | None, unacked_terminal_calls: list[str], ) -> None: """Enforce the resumption provenance invariant before the agent loop is allowed to continue on a re-attached SSE stream. Raises SessionForkDetected on any condition where the client cannot prove that the stream it is now reading is the continuation of the one it left. """ # 1. Session identity must not change under a resumption request. if response_session_id != sent_session_id: raise SessionForkDetected( f"session id changed on resume: sent={sent_session_id!r} " f"got={response_session_id!r}; terminal calls at risk: " f"{unacked_terminal_calls!r}" ) # 2. If any event was replayed, it must be strictly after the cursor # and contiguous with it. A gap means a hole in the log; a # duplicate means the cursor was already consumed. if first_replayed_event_id is not None: if first_replayed_event_id <= sent_last_event_id: raise SessionForkDetected( f"duplicate replay: cursor={sent_last_event_id} " f"first_event={first_replayed_event_id}" ) if first_replayed_event_id != sent_last_event_id + 1: raise SessionForkDetected( f"event-log gap: cursor={sent_last_event_id} " f"first_event={first_replayed_event_id}" ) # 3. If the stream is live but we hold unacknowledged terminal calls # and no replay was offered, the terminal result may have been # emitted by a replica we are no longer talking to. Do not resume # the loop; re-drive via idempotency keys instead. if first_replayed_event_id is None and unacked_terminal_calls: raise SessionForkDetected( "live stream with no replay while terminal calls are " f"unacknowledged: {unacked_terminal_calls!r}; " "outcome is UNKNOWN, re-drive with idempotency keys" ) ``` The invariant, stated once: **a resumable stream is only resumable if the receiver can prove the cursor was minted by the session it is serving.** Anything less is a fork dressed as a reconnect, and the agent will not see it — the transport will report `200` the whole way down.