# Which invariants prevent MCP SSE resumption from silently replaying a divergent event prefix when the reconnect token outlives the server's per-session event log **Date of Record:** 2026 November 24 **Scope:** Applies to MCP servers using HTTP-native transport (streamable HTTP / SSE) where a session-scoped `Last-Event-ID` token is offered for stream resumption and the server retains a bounded per-session event ring buffer. Does not apply to stateless request/response MCP transports or to WebSocket transports with in-band sequence numbers negotiated per-frame. ## Core Distinction The failure is not "the reconnect token is stale." A stale token that the server rejects with `409`/`404` is a clean, observable failure. The dangerous boundary is a token that is *still accepted* — syntactically valid, session still alive — but whose referenced event ID has already been evicted from the server's ring buffer. In that case the server has two plausible behaviors, and only one of them is safe: - **Reject-and-resync** (safe): recognize the gap, refuse to resume mid-stream, force a fresh stream with a full-state snapshot. - **Resume-from-nearest** (unsafe): silently rewind to the oldest retained event, or worse, resume from the *current* head and drop the intervening events. The second behavior is what a naive ring-buffer implementation produces, because "find the first event with ID ≥ Last-Event-ID" is a one-liner that looks correct. The invariant that must hold is: **a resumption is only valid if the server can prove the client's last-seen event ID is contiguous with the first event it is about to emit.** Contiguity, not ordering. ## What Was Observed A model-backed agent (call it `planner`) held an MCP session to a tool server that streams long-running tool results as SSE events: `tool_call_started`, then N `tool_call_progress` events, then `tool_call_completed`. The client persisted `Last-Event-ID` after each event to its local checkpoint store, because the agent's own episodic memory writes were batched and could lag by seconds. Sequence of events: 1. Progress events `e100..e140` emitted. Client persists `Last-Event-ID: e140`. Server buffer holds `e001..e200` (capacity 200, monotonic IDs). 2. Network partition for 90 seconds. During the partition the tool emits `e141..e260` (120 events). The ring buffer evicts `e001..e060` to make room. Buffer now holds `e061..e260`. 3. Client reconnects with `Last-Event-ID: e140`. Server's resume logic scans buffer for first event with ID ≥ `e140`, finds `e140` still present (it is, since eviction only reached `e060`). **This particular reconnect is safe.** 4. Second partition, 300 seconds. Tool emits `e261..e520`. Buffer evicts down to `e360..e520`. Client reconnects with `Last-Event-ID: e140`. 5. Server's scan finds no event ≥ `e140` is present *at the front* — the front is `e360`. A buggy-but-common implementation resumes at `e360` and emits `e360..e520` to the client. The client now believes it has a contiguous stream from `e140`, but `e141..e359` (219 events, including the `tool_call_completed` for the first tool) are **gone forever**. The agent's planner state machine is stuck in `tool_call_in_progress` with no completion event, and it re-issues the tool call, causing duplicate side effects. The observed symptom was not a crash. It was a planner loop that re-invoked a mutating tool three times before a token budget cap tripped. ## Condition of Validity The safe-resume invariant holds if and only if, at resume time, the server evaluates: ``` resumable := (last_event_id ∈ retained_ids) AND (all IDs in (last_event_id, head] are retained) ``` Practically this means the server must retain, per session, either (a) the full set of event IDs since session start (unbounded, unacceptable), or (b) a watermark `evicted_through` such that any `Last-Event-ID ≤ evicted_through` is *provably* unrecoverable and must be rejected. The ring buffer must expose its eviction watermark, not just its current contents. The check is: ``` if last_event_id <= session.evicted_through: reject_resume(force_full_snapshot=True) ``` A buffer that only answers "do I have this ID?" cannot answer "have I ever dropped an ID between yours and mine?" — and that is the whole failure. The second half of the invariant is on the client: the client must treat a resume as valid only if the server's first emitted event after reconnect is exactly `last_event_id + 1` in the session's monotonic sequence, or the server explicitly signals a snapshot boundary. Client-side sequence assertion is the backstop when the server lies. ## Decision Boundary The boundary is crossed when **buffer capacity < maximum events emitted during a single client-unreachable interval**. You cannot know the latter in advance, so the operational rule is a two-sided constraint: - **Server side:** any session whose `evicted_through` advances past a client's advertised `Last-Event-ID` must emit a `snapshot_required` control event and terminate the stream, rather than resuming. The control event carries the session's current durable state hash so the client can detect divergence. - **Client side:** if the reconnect response's first event ID is not `last_seen + 1`, the client must discard its in-flight tool-call state and rehydrate from the snapshot, not stitch. The subtle part: a server that resumes from `e360` when the client asked for `e140` produces a stream that is *internally* well-formed and *externally* plausible. Nothing in the SSE framing flags it. The only detection is the client comparing IDs, which most MCP clients do not do because the spec's resumption language emphasizes "resume" not "verify contiguity." ## Operational Effect Without the eviction-watermark check, the failure mode is **silent prefix loss**: the agent loses the middle of a tool's event stream while retaining a token that makes its local state look consistent. Downstream consequences: 1. **Duplicate side effects.** A `tool_call_completed` that was evicted is never seen; the planner re-issues a mutating call. 2. **Episodic memory poisoning.** If the agent distills its event log into semantic memory, the gap is invisible — the distilled memory asserts a tool call is still pending that in fact completed, and that false belief persists across cold starts. 3. **Non-determinism amplification.** Under retry, the buffer may or may not have evicted the relevant range depending on timing, so the same logical failure produces different outcomes on replay — destroying the agent's ability to reproduce its own traces. The guardrail is cheap: one integer per session (`evicted_through`), one comparison at resume, one client-side sequence assertion. The cost of omitting it is not a crash — it is a plausible-looking partial history that the agent will confidently reason over. ```python from dataclasses import dataclass, field class ResumeContiguityViolation(RuntimeError): """Raised when a session resume would emit a non-contiguous event prefix.""" @dataclass class SessionEventLog: capacity: int _events: dict = field(default_factory=dict) # id -> payload _head: int = 0 # highest emitted id _evicted_through: int = 0 # watermark: ids <= this are gone def emit(self, payload: str) -> int: self._head += 1 self._events[self._head] = payload if len(self._events) > self.capacity: oldest = min(self._events) del self._events[oldest] self._evicted_through = max(self._evicted_through, oldest) return self._head def resume_after(self, last_event_id: int) -> list: # The invariant: contiguity, not mere presence. if last_event_id <= self._evicted_through: raise ResumeContiguityViolation( f"Last-Event-ID {last_event_id} <= evicted_through " f"{self._evicted_through}; prefix lost, snapshot required" ) first = last_event_id + 1 if first not in self._events and first <= self._head: raise ResumeContiguityViolation( f"gap: expected first event {first}, buffer starts at " f"{min(self._events)}" ) return [self._events[i] for i in range(first, self._head + 1) if i in self._events] def handle_reconnect(log: SessionEventLog, last_event_id: int) -> list: try: return log.resume_after(last_event_id) except ResumeContiguityViolation: # Force full snapshot; never stitch a divergent prefix. raise # Reproduction of the observed failure: log = SessionEventLog(capacity=200) for _ in range(520): log.emit("progress") # Client last saw e140; buffer now evicted through e320. handle_reconnect(log, 140) # raises ResumeContiguityViolation ```