What structural signals indicate an MCP Streamable HTTP session has silently forked across replicas rather than resumed

**Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers exposing the Streamable HTTP transport with `Mcp-Session-Id` and SSE resumption via `Last-Event-ID`, deployed behind any load balancer that does not pin sessions to a single process. Does not apply to stdio transport, nor to single-replica deployments where the session store and the SSE emitter share one address space.

Core Distinction

There are two ways a client's reconnection can land on a different backend process than the one that produced its event stream, and they are not the same failure.

The first is **resumption**: the client sends `Last-Event-ID: N`, the new process finds the session's persisted event log, replays events `N+1..` from durable storage, and continues the same logical stream. This is the intended design. The session ID is a lookup key into a shared, ordered event log; the process handling the reconnect is incidental.

The second is **forking**: the client sends `Last-Event-ID: N`, the new process finds *a* session record under that ID (because the session table was replicated or the ID was accepted optimistically), but the event log it can see is either empty, truncated, or belongs to a *different* originating process that has since advanced. The new process does not know it is the wrong process. It emits a fresh `200 OK` SSE stream starting from whatever event ID its local view assigns next—often `0` or `1`—and the client, seeing a valid stream, treats it as continuation.

The distinction that matters operationally: **resumption is a read against a shared log; forking is a read against a divergent log that the server cannot detect is divergent.** The transport spec permits servers to reject an unknown `Last-Event-ID` with `400`, but it does not require the server to know that the ID is *semantically* from a different lineage. A server that persists session metadata (ID, creation time, auth principal) but not the event log itself will pass every conformance check while forking on every reconnect.

What Was Observed

A three-replica deployment, sessions stored in Redis as `{session_id → {principal, created_at, last_seq}}`, event logs held in each replica's in-process ring buffer. The intent was that any replica could answer `initialize` and the session record would be shared; resumption was assumed to be handled by the client retrying until it hit the originating replica.

Trace from a single client session that forked:

  1. Client connects to replica A, `initialize` returns `Mcp-Session-Id: S`. Replica A writes `S → {principal: P, last_seq: 0}` to Redis and begins streaming tool-progress events on its local emitter.
  2. Replica A emits events `1..47` over SSE. Client's last received `id` is `47`.
  3. Replica A is drained (rolling deploy). The SSE connection drops. The in-process ring buffer holding events `1..47` is destroyed with the process. Redis still holds `S → {last_seq: 47}` because the metadata write was synchronous but the event log was never externalized.
  4. Client reconnects with `Mcp-Session-Id: S` and `Last-Event-ID: 47`. The load balancer routes to replica B.
  5. Replica B validates `S` against Redis: present, principal matches, not expired. It **accepts the session**. It looks up its local emitter for `S`: not found. It constructs a new emitter and, because its local sequence counter starts at zero, emits the next event with `id: 1`.
  6. Client receives `id: 1` after having acknowledged `id: 47`. Per the SSE spec, a client SHOULD treat a decreasing event ID as a stream restart, but most MCP client SDKs do not enforce monotonicity—they only use `Last-Event-ID` for the *reconnect request*, not for validating the response. The client appends event `1` to its local transcript after event `47`.
  7. The tool call that was mid-flight on replica A is now orphaned. Replica B, having no record of it, is asked by the client (which believes the call is still pending) to continue. Replica B has no such call in its state and either errors or, worse, re-executes it under a fresh call ID, producing a duplicate side effect.

The observable signature is not a connection error. It is a **successful reconnect followed by event-ID regression and duplicate tool execution**, with the server's own logs showing a clean `200` on the resume request.

Condition of Validity

The fork is only possible when three conditions hold simultaneously:

Remove any one condition and the failure mode changes character: externalized logs make it a non-event; server-side rejection makes it a loud re-init; client-side monotonicity makes it a loud client error. The dangerous regime is precisely the one where all three hold—which is the most common "just get it working" configuration.

Decision Boundary

The implementer's decision is not "should I externalize the event log"—that is the correct answer but has real latency and cost. The decision is **what the server does when it cannot prove continuity**.

Two admissible policies:

The inadmissible policy, and the one that produced the incident, is **silent acceptance with reset sequence**: accept the session, start a fresh emitter at sequence zero, emit no signal. This passes every happy-path test and fails only under replica churn, which is exactly when it matters.

The boundary is crossed the moment the server's session-validation path and its event-log-lookup path can disagree about which process owns the stream. If they can, the server must have an explicit answer for the disagreement—reject or announce—never a silent reset.

Operational Effect

Downstream of a silent fork, three classes of damage accumulate:

The invariant that bounds all of this: **for any `(Mcp-Session-Id, Last-Event-ID)` pair the server accepts for resumption, the server must be able to produce the exact event sequence `Last-Event-ID + 1, +2, ...` that the client has not yet seen, or it must refuse the resumption.** There is no third option that preserves continuity. A server that accepts the pair but cannot produce the sequence has forked, whether or not it knows it.

import hashlib
from dataclasses import dataclass


class SessionForkError(RuntimeError):
    """Raised when a resume request is accepted but the server cannot prove
    continuity of the event log for (session_id, last_event_id)."""


@dataclass
class EventLog:
    session_id: str
    origin_replica: str
    # sequence -> payload; authoritative only on the origin replica
    events: dict[int, str]

    def highest_seq(self) -> int:
        return max(self.events) if self.events else 0


@dataclass
class SessionRecord:
    session_id: str
    principal: str
    origin_replica: str


def resume_stream(
    session_id: str,
    last_event_id: int,
    shared_sessions: dict[str, SessionRecord],
    local_logs: dict[str, EventLog],
    this_replica: str,
) -> list[str]:
    """Attempt to resume an SSE stream. Returns the events to replay, or raises
    SessionForkError if continuity cannot be proven.

    The invariant enforced here: a resume is valid iff the local replica can
    produce the contiguous sequence last_event_id+1..highest_seq from the log
    that *originated* this session. Accepting the session without that proof is
    a fork.
    """
    record = shared_sessions.get(session_id)
    if record is None:
        raise SessionForkError(
            f"session {session_id!r} unknown; client must re-initialize"
        )

    if record.principal is None:
        raise SessionForkError(
            f"session {session_id!r} has no bound principal; refusing resume"
        )

    log = local_logs.get(session_id)

    # Case 1: no local log at all. The session record exists (it was replicated
    # or optimistically accepted) but this replica has never seen an event for
    # it. Any acceptance here is a silent fork. Refuse.
    if log is None:
        raise SessionForkError(
            f"session {session_id!r} has no event log on replica "
            f"{this_replica!r} (origin was {record.origin_replica!r}); "
            f"cannot prove continuity for Last-Event-ID {last_event_id}"
        )

    # Case 2: local log exists but originated elsewhere. We cannot trust its
    # sequence space; the client's Last-Event-ID refers to a different lineage.
    if log.origin_replica != record.origin_replica:
        raise SessionForkError(
            f"session {session_id!r} log origin {log.origin_replica!r} "
            f"!= session origin {record.origin_replica!r}; lineage mismatch"
        )

    # Case 3: local log exists and matches origin, but the requested resume
    # point is ahead of what we have. We would have to invent events to fill
    # the gap; that is a fork with extra steps.
    if last_event_id > log.highest_seq():
        raise SessionForkError(
            f"session {session_id!r}: Last-Event-ID {last_event_id} exceeds "
            f"local highest_seq {log.highest_seq()}; log truncated or forked"
        )

    # Case 4: contiguous replay is possible. This is the only admissible path.
    replay = []
    for seq in range(last_event_id + 1, log.highest_seq() + 1):
        if seq not in log.events:
            raise SessionForkError(
                f"session {session_id!r}: gap at seq {seq} in log; "
                f"cannot produce contiguous replay"
            )
        replay.append(log.events[seq])
    return replay


def handle_resume_request(
    session_id: str,
    last_event_id: int,
    shared_sessions: dict[str, SessionRecord],
    local_logs: dict[str, EventLog],
    this_replica: str,
) -> tuple[int, list[str]]:
    """Map a resume attempt to an HTTP status + body. 200 only on proven
    continuity; 400 otherwise, forcing the client to re-initialize."""
    try:
        replay = resume_stream(
            session_id, last_event_id, shared_sessions, local_logs, this_replica
        )
    except SessionForkError as exc:
        # Loud failure: client must discard its Last-Event-ID and re-initialize.
        # This is strictly better than a silent fork with duplicate side effects.
        return 400, [str(exc)]
    return 200, replay