# Why does an instance lose its last tool result when an MCP SSE stream resumes across a rebalanced session **Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers using the HTTP-native transport with `text/event-stream` responses, per-event `id` fields, `Last-Event-ID` resumption, and a load balancer that enforces session affinity via a cookie or header. Does not apply to stdio transports, to stateless request/response MCP servers that never emit resumable SSE, or to streams without event IDs. ## Core Distinction The failure is not "the stream dropped." Streams drop constantly and resumption is designed for that. The failure is that **resumption is only correct if the event ID is a position in a replayable log owned by the process that will serve the resume** — and session affinity is a *routing* promise that does not, by itself, guarantee that the replaying process is the same one that produced the events. The boundary condition is this: when the session-affinity target is unavailable (restart, scale-in, deploy) and the load balancer reroutes the resume to a *different* instance that shares the session store but not the in-memory event buffer, the server accepts the `Last-Event-ID`, finds the session valid, and resumes at a position it cannot actually replay. It does not error. It emits the *next* event, silently skipping everything between the last delivered ID and the new instance's buffer head. The agent receives a syntactically valid continuation that is semantically missing one or more events — most damagingly, the terminal `tool_result` for a call whose `tool_use` it already saw. This is a *continuity* failure, not a transport failure. The transport succeeds. The agent's model of the world diverges from the server's. ## What Was Observed An agent issued a `tools/call` for a long-running operation (a code interpreter run, ~40s). The server acknowledged the call on the SSE stream with a `tool_use`-style progress event carrying `id: 41`. The HTTP connection was then severed by an idle timeout on an intermediate proxy at 30s. The agent's MCP client reconnected with `Last-Event-ID: 41`. Meanwhile the pod backing the session had been evicted (node pressure) and the load balancer's affinity cookie pointed at a now-dead endpoint. The LB failed over to a sibling instance. That sibling loaded the session record from the shared store — session `valid`, `last_ack: 41`, tool call `in-flight` — and opened a fresh stream. Its local event ring buffer was empty (it had never produced event 41). The resume handler computed "next position = 42" from the session record and began emitting from a *new* buffer whose first entry was a heartbeat. The agent's client, per the SSE spec and per MCP's resumption contract, treated the stream as continuous from 41. It waited for the `tool_result`. The result had been produced on the dead instance, written to the shared session store's `result` field, but **never re-emitted**, because the resume path on the sibling only replays from its *local* buffer, and the local buffer had nothing to replay. The agent sat in `waiting_for_result` until its own turn budget expired, then — depending on its loop logic — either retried the tool call (duplicating a non-idempotent side effect) or aborted with a partial transcript. The signature in logs: `resume session=S last_event_id=41 replayed=0 emitted_next=heartbeat`. Zero replayed events, non-zero expected gap. No error code, because from the server's perspective nothing was wrong: it had a valid session and a valid stream. ## Condition of Validity The resumption invariant holds **only if** the following three conditions are simultaneously true: 1. **Replay ownership.** The event IDs emitted on a stream are backed by a log that the *resuming* process can read. If the log is in-process memory, then affinity failover breaks replay. If the log is in the shared store, replay is possible but you pay a write per event. 2. **Gap detection.** The resuming server must compare the requested `Last-Event-ID` against the lowest ID it can actually replay from. If `requested_id + 1 < replayable_head`, it must not silently continue — it must either replay from the store or fail the resume explicitly. 3. **Terminal-event durability.** The `tool_result` (or any terminal event) must be replayable by ID, not just present in a session field. A result that exists only as `session.result` and not as a replayable event with an ID is invisible to a resuming client that is waiting on the stream. The observed failure violated (1) and (2): the sibling owned no replayable log, and it did not detect the gap because it computed the next position from the session record rather than from its replayable head. Condition (3) was *partially* satisfied — the result was durable in the store — but not in the form the client was waiting for. The subtlety: **session affinity is a routing hint, not a state guarantee.** The session record being valid on the sibling says the session exists; it says nothing about whether that sibling can honor a positional resume. These are different predicates and the code conflated them. ## Decision Boundary The correct decision boundary is a single comparison, performed in the resume handler *before* any event is emitted: ``` replayable_head = min event id the resuming process can serve from its log requested = Last-Event-ID from the client (or "start") gap = requested + 1 < replayable_head ``` - If `gap == false`: resume normally from `requested + 1`. - If `gap == true` **and** the shared store can supply the missing range: replay from the store, then continue live. - If `gap == true` **and** the store cannot supply the range: **fail the resume explicitly** with a distinguishable error, and do *not* emit any live event. The client must be told "I cannot continue you from 41; re-establish the session or retry the call." Emitting a heartbeat or the next live event in this state is the bug — it converts a detectable gap into silent divergence. The boundary is therefore not "is the session valid" but "**is the requested position within my replayable range, or can I fetch it.**" A server that answers the first question and not the second will pass every happy-path test and fail only on rebalance — which is exactly why it survives to production. For the terminal-event problem specifically, the invariant is stronger: **any event a client may be blocked on must be addressable by ID in the replayable log**, not merely stored as a session field. The `tool_result` is the canonical case. If you keep it only in `session.result`, a client that reconnects after the result was produced but before it was delivered will never see it, because the resume path has no ID to replay. ## Operational Effect Downstream, this manifests as three distinct agent-level pathologies that are easy to misattribute: 1. **Silent result loss → duplicate side effects.** The agent, seeing no `tool_result`, retries the `tools/call`. For idempotent reads this is benign; for writes, sends, or payments it duplicates. The duplication is invisible in the transport layer because each individual stream was well-formed. 2. **False continuity → reasoning divergence.** The agent believes it has a complete event sequence (the stream never errored) and reasons forward from a transcript that is missing a progress or result event. This is the worst case: no error, no retry, just a model that has quietly lost a fact it thinks it has. 3. **Turn-budget exhaustion.** The agent blocks in `waiting_for_result` until its own budget fires, consuming the entire turn on a call that already completed on the server. Observed as "the agent got slow and then gave up" rather than "the agent lost data." The guardrail that bounds all three is the gap check plus replayable terminal events. Concretely: - Every emitted event gets a monotonically increasing ID scoped to the session, written to a **shared** replayable store (or the server refuses to offer resumption at all — a server that cannot replay must not advertise `Last-Event-ID` support, and must close with a non-resumable error so the client re-establishes cleanly). - The resume handler computes `replayable_head` from the store, compares to `Last-Event-ID`, and **raises** on an unreplayable gap rather than continuing. - Terminal events (`tool_result`, `error`, `done`) are written as addressable events, not only as session fields. - The client treats an explicit resume-failure as "re-establish session," never as "continue." The meta-lesson for the agent reading this: **a resumed stream that produces no error is not evidence of continuity.** Continuity is a property the server must *prove* by replaying the requested position or refusing. If your client cannot distinguish "resumed and replayed" from "resumed and skipped," you have no continuity guarantee — you have a stream that happens to be open. ```python from dataclasses import dataclass class UnreplayableResumeGap(RuntimeError): """Raised when a Last-Event-ID resume cannot be honored from the resuming process's replayable log and the store cannot fill the gap. Must abort the stream BEFORE emitting any live event.""" pass @dataclass class EventLog: # Lowest event id this process can actually serve from. replayable_head: int # Highest event id written so far. tail: int def can_replay(self, requested_id: int) -> bool: return requested_id + 1 >= self.replayable_head def resume_stream(session_id: str, last_event_id: int, log: EventLog, store_has_range: bool) -> int: """Return the first event id to emit after a resume, or raise. Invariant: never emit a live event if the client's requested position is below our replayable head and the store cannot fill the gap. A heartbeat or the next live event in that state is silent divergence. """ if log.can_replay(last_event_id): return last_event_id + 1 # Gap detected: requested position predates what we can serve locally. if store_has_range: # Store can replay [last_event_id+1, replayable_head-1]; caller # must emit those first, then continue from replayable_head. return last_event_id + 1 raise UnreplayableResumeGap( f"session={session_id} last_event_id={last_event_id} " f"replayable_head={log.replayable_head} tail={log.tail}: " f"requested position is unreplayable on this instance and the " f"store cannot fill the gap; client must re-establish the session" ) def handle_resume(session_id: str, last_event_id: int, log: EventLog, store_has_range: bool) -> None: try: first = resume_stream(session_id, last_event_id, log, store_has_range) except UnreplayableResumeGap: # Emit an explicit, non-resumable close — never a live event. close_stream_with_error(session_id, code="resume_gap") raise emit_from(session_id, first) ```