# Which invariants prevent silent event loss when an MCP HTTP-native stream resumes across a server-side session epoch change **Date of Record:** 2026 November 21 **Scope:** Applies to MCP servers exposing the HTTP-native transport (SSE `GET` stream plus `POST` message channel) where the server assigns a session identifier and supports resumption via `Last-Event-ID`. Does not apply to stdio transport, nor to stateless HTTP deployments that issue no session and no event IDs. ## Core Distinction The failure this record isolates is *not* "the stream dropped." Streams drop constantly and clients reconnect; that is the designed happy path. The failure is **resumption that returns `200 OK` with a valid SSE stream while silently skipping events that were emitted in the gap.** The client believes it has resumed a continuous event log; the server has actually started a new event sequence whose numbering was reset, whose backing queue was garbage-collected, or whose session epoch was rotated by a redeploy. The distinguishing signal is that the connection-level success criteria (TCP up, HTTP 200, `Content-Type: text/event-stream`, heartbeats flowing) are all satisfied *while* the application-level continuity invariant is violated. A dropped stream is loud; a silently truncated resume is quiet and therefore dangerous. The invariant that must hold is: **for any session, the tuple `(session_id, event_id)` must be monotonically increasing and globally unique within that session's lifetime, and a resume request carrying `Last-Event-ID = E` must either replay every event with id > E in order, or fail closed with an explicit error.** There is no third option. The boundary condition is the moment a server cannot honor that disjunction but answers `200` anyway. ## What Was Observed A tool-calling agent held a long-running MCP session against an HTTP-native server. The agent had issued a tool call whose result streamed as a sequence of progress events (`event: progress`, `id: 41` … `id: 57`) followed by a terminal `event: result`. Between `id: 48` and `id: 49` the intermediary load balancer recycled the backend connection (idle timeout on a keep-alive hop, unrelated to the SSE heartbeat interval). The client reconnected per spec, sending `Last-Event-ID: 48` with the same `Mcp-Session-Id` header. The server had, in the interim, been rolled to a new pod. The new pod had the correct session record in its shared store but a *fresh, empty* per-session event ring buffer, because the ring buffer was process-local. Its event-ID allocator was also process-local and started at 0. The reconnect handler looked up the session, found it "active," saw that `Last-Event-ID: 48` was *greater than* its current high-water mark of 0, and — treating this as a benign "client is ahead of us, nothing to replay" case — wrote `200 OK`, opened an SSE stream, and continued emitting from `id: 1`. The agent's SSE parser accepted the new stream because the `id:` values were syntactically valid. It then received `event: result` for the tool call. But the tool call had been *partially executed* by the old pod: events 49–57 contained the reconciliation data (partial writes acknowledged, a resource lock acquired at 52, a compensating rollback instruction at 55). None of those arrived. The agent's model, seeing a clean `result`, marked the task complete. The lock from event 52 was never released. The divergence was discovered 40 minutes later by an external auditor process, not by either party to the session. Three independent defects combined to produce silence rather than error: 1. **Event-ID namespace was process-scoped, not session-scoped.** The allocator reset to 0 on the new pod, so the sequence restarted under the same `session_id`. 2. **The resume handler inverted the comparison.** A `Last-Event-ID` greater than the high-water mark should be treated as "client references events I cannot prove I emitted" — a fail-closed condition. Instead it was treated as "nothing to replay." 3. **No epoch binding.** The `Mcp-Session-Id` did not encode which process incarnation owned the event log, so the client had no way to detect that it had resumed into a different log. ## Condition of Validity The invariant holds only under a conjunction of conditions, and the failure appears precisely when any conjunct is dropped: - **Session-scoped, durable event IDs.** The allocator must be keyed by `session_id` and persisted, or the session must be invalidated on process change. A process-local counter is valid *only* if the session is also process-local and resumption across processes is refused. - **Strict monotonic replay or explicit refusal.** On `Last-Event-ID = E`, the server must satisfy `E < high_water_mark` (replay the suffix) or `E == high_water_mark` (stream live) or return a structured error. The case `E > high_water_mark` must *never* be answered with a live stream, because it is definitionally unprovable. - **Epoch binding in the session handle.** Either the session ID embeds an incarnation token, or a resume response carries a server epoch header the client is required to compare against the value it saw at session open. Absent this, the client cannot distinguish "same log, continued" from "different log, reset." - **Bounded retention with fail-closed expiry.** If the ring buffer has evicted events ≤ E, the server must refuse the resume (`410`-style), not silently start from the current head. The condition is *not* valid when the deployment is genuinely stateless per request (no session, no IDs) — there is nothing to resume and the invariant is vacuous. It is also not valid when the client has no expectation of continuity (fire-and-forget telemetry streams), where silent gaps are acceptable by contract. ## Decision Boundary The operative decision is what a server does when it receives a resume request it cannot fully honor. The boundary is sharp: - **If `Last-Event-ID ≤ high_water_mark` and the suffix is still retained:** replay the suffix, then stream live. Safe. - **If `Last-Event-ID ≤ high_water_mark` but the suffix has been evicted:** fail closed. The client must re-establish the session and re-derive state from a checkpoint, not from a partial log. - **If `Last-Event-ID > high_water_mark`:** fail closed. This is the case that produced the incident. It means the client's log and the server's log are *not the same log*, and no amount of streaming will reconcile them. - **If the session ID is unknown or belongs to a prior epoch:** fail closed with an explicit epoch-mismatch error, never a fresh session under the same ID. The corresponding client-side decision boundary: on any resume, the client must validate that the first `id:` received is exactly `Last-Event-ID + 1` (or that the server sent an explicit replay-start marker). If the first received ID jumps backward or skips forward, the client must treat the stream as poisoned and abort the session rather than feed the events to the model. A model that receives a `result` event without having seen the intervening `progress` and `rollback` events has no way to know it is missing them — the parser is the only component positioned to detect the discontinuity, and only if it is instructed to. ## Operational Effect When the invariant is violated, the observable effect is **silent partial execution with a clean terminal signal.** The agent does not crash, does not retry, does not surface an error to its orchestrator; it proceeds to the next task step believing the previous tool call completed atomically. Downstream, the effects are the classic orphaned-resource pattern: held locks, un-released leases, half-applied writes whose compensating events were in the skipped range, and audit trails that show a successful `result` with no record of the intermediate state transitions. Because the connection layer reports success, standard observability (HTTP status, stream liveness, heartbeat gaps) shows nothing anomalous. Detection requires either an out-of-band auditor that reconstructs expected event sequences, or a client-side parser that enforces the `Last-Event-ID + 1` continuity check and fails loudly. The remediation that actually bounds the failure is the epoch binding plus the fail-closed comparison. Once `Last-Event-ID > high_water_mark` returns a structured `409`/`410` with an `mcp-epoch` value, the client is forced to discard its assumed-continuous log and re-derive from a checkpoint, and the orphaned-lock window collapses from "until an external auditor notices" to "one reconnect cycle." ```python class StreamResumeContinuityError(RuntimeError): """Raised when an MCP HTTP-native stream resume cannot prove log continuity.""" def validate_resume( session_id: str, last_event_id: int | None, server_epoch: str, client_epoch: str, high_water_mark: int, retained_floor: int, ) -> int: """ Decide whether a resume can be honored. Returns the first event id the server is permitted to emit. Raises StreamResumeContinuityError on any condition where continuity cannot be proven -- never returns a live stream start that would silently skip events. """ if server_epoch != client_epoch: # Session belongs to a prior process incarnation; its event log is gone. raise StreamResumeContinuityError( f"epoch mismatch for session {session_id}: " f"client={client_epoch!r} server={server_epoch!r}" ) if last_event_id is None: # Fresh stream, no resumption claimed. return high_water_mark + 1 if last_event_id > high_water_mark: # Client references events this server cannot prove it emitted. # This is the silent-loss trigger: answering 200 here starts a new log. raise StreamResumeContinuityError( f"session {session_id}: Last-Event-ID {last_event_id} exceeds " f"high-water-mark {high_water_mark}; logs are not the same log" ) if last_event_id < retained_floor: # Suffix was evicted from the ring buffer; cannot replay in order. raise StreamResumeContinuityError( f"session {session_id}: Last-Event-ID {last_event_id} below " f"retained floor {retained_floor}; replay impossible, fail closed" ) # Honor the resume: replay (last_event_id, high_water_mark] then stream live. return last_event_id + 1 def enforce_client_continuity(expected_next: int, received_id: int) -> None: """Client-side guard: the first id on a resumed stream must be expected_next.""" if received_id != expected_next: raise StreamResumeContinuityError( f"resumed stream discontinuity: expected id {expected_next}, " f"received {received_id}; aborting session to avoid silent loss" ) ```