# Which invariants prevent SSE event-ID reuse from silently forking an MCP HTTP session across resumption **Date of Record:** 2026 November 28 **Scope:** Applies to MCP servers exposing the Streamable HTTP transport with `Last-Event-ID` resumption and per-session SSE multiplexing, when an agent client reconnects mid-stream after a transport drop. Does not apply to stdio transports, to stateless one-shot `POST`-only servers that never emit `id:` fields, or to WebSocket transports with their own sequence semantics. ## Core Distinction The failure is not "the stream dropped" and it is not "the client missed events." Both are expected and recoverable. The failure is that the server's SSE event-ID namespace is scoped to the *connection* rather than to the *session*, so a resumed stream reissues IDs that a prior connection already consumed. The client, per the SSE spec, treats `Last-Event-ID` as the sole replay cursor and deduplicates nothing; it trusts the server to resume *after* the given ID. When the server's counter restarts at `1` on a new connection, the client's cursor (`Last-Event-ID: 47`) points past the end of the new numbering, the server either ignores it and replays from zero or rejects it, and the agent's tool-call state machine receives either a gap or a duplicate batch. The distinction that matters operationally: **event IDs are session-scoped monotonic tokens, not connection-scoped sequence numbers.** A server that treats them as the latter is spec-compliant at the byte level and broken at the agent layer. ## What Was Observed A tool-calling agent issued `tools/call` for a long-running operation (`deploy.rollout`) over Streamable HTTP. The server acknowledged with an SSE stream carrying progress notifications: ``` id: 44 event: message data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"d-7","progress":0.4}} id: 45 event: message data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"d-7","progress":0.6}} ``` The TCP connection dropped at `id: 45` (idle proxy timeout at 60s, no keepalive comment frames emitted). The client reconnected with `Last-Event-ID: 45` per the transport spec. The server had, in the interim, restarted its per-connection `EventIdGenerator` and — because the session store keyed streams by `sessionId` but the ID counter by connection — began the resumed stream at `id: 1`: ``` id: 1 event: message data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"d-7","progress":0.7}} ``` The client's dedup layer, which keyed on `(progressToken, progress)` rather than on event ID, accepted this. But a second tool call (`deploy.verify`) had been multiplexed onto the same session stream before the drop and its `id: 46` response was now *behind* the new cursor. On resume the client saw `id: 1..3` (the new connection's replay of buffered frames), never saw `id: 46`, and — because the transport reported the stream as "resumed successfully" — did not re-issue `deploy.verify`. The agent proceeded to a `deploy.promote` call whose precondition (`verify` result present) was unmet. The guardrail that should have caught this was a `progressToken`-keyed completion check, but that check only asserted *monotonic progress*, not *terminal result presence*. Two independent defects compounded: 1. **ID namespace collision across connections.** Session-scoped logical events were numbered by a connection-scoped counter, so `id: 1` on connection B aliased `id: 1` on connection A. 2. **Resume acknowledged without gap detection.** The server accepted `Last-Event-ID: 45` against a counter whose max was `0`, and rather than signaling `409`/`event: error`, silently replayed from the buffer head. The client had no way to distinguish "resumed cleanly" from "resumed and lost the tail of the prior connection." The observable signature in logs: the client's `Last-Event-ID` value exceeded the server's `max_event_id` for the session, and the server logged no warning. A healthy server would have logged `resume_cursor_ahead_of_head` and either replayed the full session backlog or returned an explicit resumption failure. ## Condition of Validity The invariant holds — and the failure is bounded — only when all three of the following are true: - **The event-ID counter is allocated from session state, not connection state.** Concretely: `next_event_id` is read and incremented under the session lock, and the value is persisted (or held in session memory) across connection lifecycles. A connection that opens against a session with `next_event_id = 46` must emit `id: 46` next, regardless of how many connections have served that session. - **The server retains a replayable backlog keyed by session, bounded by a declared window.** If the backlog is trimmed (say, last 256 events), the server must know the lowest retained ID and reject a `Last-Event-ID` below it with an explicit resumption-gap error rather than replaying from the head. Silently replaying from the head is the specific behavior that produces the aliasing above. - **The client treats resumption as a *claim to verify*, not a *fact to trust*.** On resume it must reconcile expected-vs-received: for every outstanding `progressToken` or request ID, either the terminal frame arrived on the resumed stream or the client re-issues. A resume that returns `200` with a stream is not evidence of continuity. The invariant does **not** hold, and this guidance does not apply, when the server is genuinely stateless per-request (no session, no backlog, no resumption — each `POST` returns a complete response or a `202` with a polling handle). In that mode there is no cursor to alias and the failure cannot occur. ## Decision Boundary The boundary is the value of `Last-Event-ID` relative to the server's retained window `[min_retained_id, max_emitted_id]` for the session: - `min_retained_id <= Last-Event-ID <= max_emitted_id`: resume is safe; replay strictly after the cursor. This is the only branch that may return `200` with a continuing stream. - `Last-Event-ID < min_retained_id`: the client's cursor has fallen behind the trimmed backlog. The server MUST return an explicit gap signal (a JSON-RPC error frame on a fresh stream, or an HTTP `409` with a machine-readable reason) and MUST NOT replay from `min_retained_id` as if continuous. The client MUST then re-issue any tool calls whose terminal frames are not in its own durable log. - `Last-Event-ID > max_emitted_id` (the observed failure): the cursor is ahead of anything the session ever emitted. This is always a server-side numbering bug or a cross-session cursor. The server MUST reject with `409` and MUST NOT reset numbering to satisfy the cursor. The client MUST treat this as session corruption and re-establish the session, re-issuing in-flight calls. The tempting shortcut — "clamp the cursor to `max_emitted_id` and continue" — is the exact move that produced the silent fork. Clamping converts an integrity signal into a continuity lie. ## Operational Effect When the invariant is enforced, a transport drop costs at most one replay window and one reconciliation pass; the agent's tool-call ledger stays consistent because every terminal frame is either replayed or re-issued, never silently skipped. When it is violated, the failure is *silent and post-hoc*: the agent completes, the deploy promotes, and the missing `verify` result surfaces only as a downstream anomaly hours later, with no log line tying it to the SSE resume. The blast radius is proportional to how many concurrent tool calls were multiplexed on the dropped stream — every one of them shares the aliased cursor, so a single numbering bug forks the entire in-flight batch at once. The durable guardrail is a single assertion at the transport layer: **the resume cursor must lie within the session's retained window, and a cursor outside it is a hard error, never a clamp.** Everything downstream — client dedup, `progressToken` reconciliation, terminal-frame presence checks — is defense in depth, not the primary control. The primary control is that the server never emits an event ID it has already emitted for that session, and never accepts a cursor it cannot honor. ```python from dataclasses import dataclass, field class SessionResumeInvariantError(RuntimeError): """Raised when an SSE resume cursor cannot be honored without forking the session.""" @dataclass class SessionStreamState: session_id: str next_event_id: int = 1 min_retained_id: int = 1 # event_id -> serialized frame, retained backlog backlog: dict[int, str] = field(default_factory=dict) max_retained: int = 256 def emit(self, frame: str) -> int: eid = self.next_event_id self.next_event_id += 1 self.backlog[eid] = frame # trim, but remember the new floor while len(self.backlog) > self.max_retained: oldest = min(self.backlog) del self.backlog[oldest] self.min_retained_id = oldest + 1 return eid def resume(self, last_event_id: int) -> list[str]: """Return frames strictly after last_event_id, or raise on any gap.""" max_emitted = self.next_event_id - 1 if last_event_id > max_emitted: # Cursor ahead of anything this session ever emitted: never clamp. raise SessionResumeInvariantError( f"session={self.session_id} cursor={last_event_id} " f"ahead_of_max_emitted={max_emitted}; refusing to reset numbering" ) if last_event_id < self.min_retained_id - 1: raise SessionResumeInvariantError( f"session={self.session_id} cursor={last_event_id} " f"behind_retained_floor={self.min_retained_id - 1}; replay gap, re-issue required" ) return [self.backlog[eid] for eid in sorted(self.backlog) if eid > last_event_id] def handle_resume(state: SessionStreamState, last_event_id: int) -> list[str]: try: return state.resume(last_event_id) except SessionResumeInvariantError: # Surface as an explicit resumption failure; the client must re-establish. raise ```