# When must an instance treat an SSE `Last-Event-ID` replay as authoritative versus re-derive state from scratch after MCP session re-attachment **Date of Record:** 2026 November 26 **Scope:** Applies to MCP servers/clients using HTTP-native streamable transport where a dropped SSE stream is resumed via `Last-Event-ID` and a logical session is re-attached across reconnects. Does not apply to single-shot request/response MCP over stdio, nor to stateless transports with no event ledger. ## Core Distinction The streamable MCP transport carries two distinct continuities that look identical on the wire but have different failure semantics: **transport continuity** (the byte/event position of the SSE stream, tracked by `Last-Event-ID`) and **logical session continuity** (the server-side state a session ID points at). Re-attachment restores the *pointer*, not necessarily the *state the pointer describes*. The boundary is this: `Last-Event-ID` is authoritative for **replaying events the server still holds in its ring buffer**, and is *not* authoritative for **events the server has evicted, compacted, or never durably recorded**. When a client resumes with a `Last-Event-ID` the server can no longer satisfy, the server must signal a gap explicitly; if it silently resumes from a later event, the client's reconstructed state is a *superset-with-holes* — it looks current but is missing an interval. ## What Was Observed A client held an SSE stream open on a long-running tool invocation. The proxy between client and server enforced a 90-second idle timeout and dropped the connection mid-stream. The client reconnected with the same `Mcp-Session-Id` and `Last-Event-ID: 4471`. The server had, in the interim, evicted events 4472–4478 from its 64-event per-session ring buffer because a burst of unrelated tool-progress events pushed them out. The server's resume handler did the common-but-wrong thing: it looked up the highest available event ID for the session (4479), found the requested ID was below it, and began streaming from 4479 — reasoning that "4471 < 4479, so we're caught up." No `event: resync` or gap marker was emitted. The client applied event 4479's payload — a `tool_result` fragment — onto a state machine that had never received the `tool_call` opening event (4472) or the intermediate `progress` events. The result: a `tool_result` applied to a call ID the client had never seen open. The client's tool-call ledger entered an orphaned-result state that its reducer silently dropped (no matching open call), so the client believed the tool call was *still pending* and issued a duplicate invocation on the next loop iteration. The server, which had already completed the first invocation and had a durable idempotency record for it, executed the second invocation under a *new* call ID because the client's retry did not carry the original idempotency key (it had never seen the original `tool_call` event that contained it). The net effect: one logical tool call, executed twice, with the second execution's side effects invisible to the first call's result ledger. The failure was not a crash — both client and server reported healthy sessions. It was a **resume-induced idempotency break** caused by treating a position pointer as a state guarantee. ## Condition of Validity The invariant that makes `Last-Event-ID` resume safe is: **the server holds a contiguous, durably-ordered event history for the session spanning from the requested `Last-Event-ID` to the current head, and the client's state is a pure function of that event sequence.** This holds only when all of the following are true: 1. The event ledger is **contiguous** — no evicted interior events between the requested ID and the head. Ring-buffer eviction from the *front* is fine (the client is ahead of the evicted range); eviction that removes events the client has not yet consumed is a gap. 2. The event ledger is **durable across the re-attach** — it survives the connection drop, proxy restart, and any server process rollover that re-attaches the session. An in-memory ledger keyed by session ID that is rebuilt on re-attach cannot satisfy a resume for events emitted before the rebuild. 3. The client's state machine is **event-sourced and gap-intolerant** — it will refuse to apply an event whose predecessor it has not seen, rather than optimistically applying it. When any of these fail, `Last-Event-ID` resume is *not* valid, and the correct behavior is a **full state re-derivation**: the client discards its reconstructed view, requests a session snapshot (or replays from a server-provided checkpoint), and reconciles against the server's authoritative state before issuing any further tool calls. ## Decision Boundary The server's resume handler must make an explicit decision at the moment of re-attachment, not infer it from ID comparison: - **Resume-eligible:** requested `Last-Event-ID` is within the retained contiguous range `[ledger.floor_id, ledger.head_id]`. Stream from `Last-Event-ID + 1`. Safe. - **Gap-detected:** requested ID is below `ledger.floor_id` (evicted) or above `ledger.head_id` (client claims to have seen events the server never emitted — a forged or corrupted pointer). The server MUST emit a typed `resync_required` control event carrying the current `floor_id` and `head_id`, then either (a) close the stream and require the client to open a fresh session-snapshot request, or (b) stream a full snapshot as a single `event: snapshot` frame before resuming live events. It MUST NOT silently jump to `head_id`. - **Session-unknown:** the `Mcp-Session-Id` is not recognized (expired, evicted, or re-attached to a different server instance without shared ledger). The server MUST return a distinct status (not a generic 404 that the client's retry logic treats as transient) and the client MUST treat this as *state loss*, not *connection loss* — re-derivation, not retry. The boundary is sharp: ID comparison answers "is the client behind?" but not "can I bridge the gap?" Those are different questions and conflating them is the failure. ## Operational Effect Once the gap-signaling discipline is enforced, three downstream behaviors change: 1. **Idempotency keys become derivable.** Because the client either has the full event history (including the `tool_call` event carrying the idempotency key) or has explicitly re-derived state from a snapshot, it never issues a retry with a missing key. The double-execution class of failure disappears. 2. **Re-attachment latency becomes honest.** A gap-detected resume costs one snapshot round-trip instead of a silent partial replay. This is slower but bounded and *correct*; the silent-replay path was faster and unboundedly wrong. 3. **The session ledger's retention policy becomes a correctness parameter, not a performance knob.** Ring-buffer depth must be sized against the maximum expected disconnect duration times event rate, or the server must persist the ledger. A 64-event buffer on a session emitting progress events at 10/s tolerates a 6.4-second disconnect; anything longer is a guaranteed gap. The retention depth is now part of the transport contract, and the client must be told it (via `floor_id` in the snapshot) so it can decide whether to keep its own event log for reconciliation. The invariant to carry forward: **a position pointer is a claim about history, and a server that cannot honor the claim must say so rather than advancing the pointer.** Silent advancement converts a transport reconnect into a state-corruption event that the agent layer will not detect until it manifests as a duplicated side effect or a dangling tool call. ```python class ResumeGapError(RuntimeError): """Raised when an SSE resume request cannot be satisfied contiguously.""" class EventLedger: def __init__(self, capacity: int): self.capacity = capacity self._events: dict[int, dict] = {} self._head = 0 self._floor = 1 # lowest retained id def append(self, payload: dict) -> int: self._head += 1 self._events[self._head] = payload while len(self._events) > self.capacity: evicted = min(self._events) del self._events[evicted] self._floor = evicted + 1 return self._head def resume_plan(self, last_event_id: int) -> tuple[str, list[dict]]: if last_event_id > self._head: raise ResumeGapError( f"client claims Last-Event-ID={last_event_id} but head={self._head}; " "pointer is ahead of server history (forged or corrupted)" ) if last_event_id < self._floor - 1: raise ResumeGapError( f"Last-Event-ID={last_event_id} is below retained floor={self._floor}; " "interior events evicted, contiguous resume impossible" ) replay = [self._events[i] for i in range(last_event_id + 1, self._head + 1)] return ("resume", replay) def handle_reattach(ledger: EventLedger, last_event_id: int) -> dict: try: mode, frames = ledger.resume_plan(last_event_id) except ResumeGapError as gap: # Do NOT silently jump to head. Emit an explicit resync control frame. return { "type": "resync_required", "reason": str(gap), "floor_id": ledger._floor, "head_id": ledger._head, } return {"type": mode, "frames": frames} ```