# How does an instance detect that an MCP resumable stream token has been silently rebound to a different session-affinity shard **Date of Record:** 2026 November 25 **Scope:** Applies to MCP clients resuming a long-running `tools/call` stream via a previously issued `Last-Event-ID`/resume token after the transport layer has rebalanced session affinity (rolling deploy, shard eviction, or connection-pool recycling). Does not apply to stateless request/response MCP calls, nor to single-process servers with no affinity layer in front of them. ## Core Distinction There are two failure classes that look identical at the client's `resume` call but diverge completely in consequence: 1. **Token rejection** — the server *knows* the token is invalid and returns an error (e.g. `-32602`, or a 404/410 on the SSE endpoint). This is loud, cheap, and safe. 2. **Token acceptance with silent rebinding** — a *different* server instance accepts the resume token because the token is syntactically valid and its embedded session ID still resolves, but the in-memory stream buffer that the token's `Last-Event-ID` offset indexes into does not exist on this shard. The instance then behaves in one of two ways, both wrong: it either (a) replays from the *start* of the tool execution because it has no buffer and treats offset as advisory, or (b) synthesizes an empty continuation and closes the stream with a normal `end`, which the client reads as "task finished." The distinction that matters: **token validity is not stream-identity continuity.** A resumable token is a *pointer into a per-shard, in-memory event log*. If the token is portable across shards but the log is not, the token's semantics are broken while its syntax remains valid. The client cannot distinguish "resumed correctly," "replayed from zero," and "resumed into a void" from the wire alone unless the protocol carries an explicit stream-identity witness. ## What Was Observed A long-running `tools/call` (a code-analysis tool emitting incremental `notifications/message` progress events over a streamable-HTTP MCP transport) was configured with a resume token scheme: token = `HMAC(session_id || stream_id || last_event_seq)`, plus a server-side map `stream_id -> ring buffer of events`. The buffer lived in process memory. A load balancer in front used a sticky cookie for session affinity. During a rolling deploy, shard `B` was drained. The client's SSE connection dropped mid-stream at event seq 412 of an expected ~900. The client, per spec, reconnected with `Last-Event-ID: 412` and its resume token. The load balancer — having already retired the sticky cookie for the drained shard — routed the reconnect to shard `C`. Shard `C` validated the HMAC (the signing key is shared fleet-wide — this is the first mistake), found `session_id` in its session table (sessions were replicated — second enabling condition), and looked up `stream_id` in its local buffer map. **Miss.** The buffer was never replicated. Shard `C`'s handler had this logic: ```python events = self.buffers.get(stream_id, []) for ev in events[last_event_seq:]: yield ev # buffer empty -> loop yields nothing -> stream closes normally ``` The client received a clean stream close with zero events after seq 412. Its completion detector treated a normal close as task completion. The tool had actually been executing on shard `B` and had produced results for seq 413–900 — but `B` was draining, its buffer discarded on shutdown, and the tool's final result was written to a result store keyed by `session_id` that `C` never consulted because it thought the stream had simply ended. Observed symptoms, in order of how they were found: - Downstream consumer logged "analysis complete, 0 findings" for a task that had 47 findings. - The result store *did* contain the 47 findings, written by `B` ~40s after `C` closed the stream. Two writers, one session, no reconciliation. - A retry on a third shard replayed the tool from seq 0, re-running a 6-minute computation and double-appending to the result store. The failure was silent for 11 minutes because every layer reported success: HMAC valid, session found, stream closed cleanly, HTTP 200. ## Condition of Validity The resumable-stream contract is only sound when **all three** of the following hold simultaneously. Drop any one and silent rebinding becomes possible: 1. **Buffer locality is guaranteed by affinity.** The resume token must route to the shard that owns the buffer. This requires the token (or the routing layer) to encode the *owning shard*, not merely the session. Session affinity is insufficient because a session can outlive a shard and be re-homed; the *stream* cannot be re-homed without its buffer. 2. **Resume is a two-sided handshake, not a lookup.** The server must confirm it possesses the buffer covering `last_event_seq` before emitting anything. A miss must be a hard error, never an empty success. The correct response to "I have no buffer for this stream" is `410 Gone` / a resume-specific error, forcing the client into an explicit *restart-or-abandon* decision. 3. **The stream carries an identity witness the client can check.** At minimum, the first event after resume must echo `(stream_id, resume_from_seq, expected_total_or_epoch)`. If the client asked to resume at 412 and the first replayed event is seq 0, or the stream epoch differs, the client must abort rather than accept. The invariant, stated precisely: **for any resume at offset `k`, the server must emit a contiguous event sequence starting at exactly `k+1`, drawn from the same execution epoch that produced events `1..k`; if it cannot prove both, it must fail closed.** "Empty and close" violates contiguity. "Replay from 0" violates offset. Both are accepted by naive clients because the transport succeeded. ## Decision Boundary The boundary is between *resumable* and *replayable*, and it is decided by whether execution state is reconstructible off-shard: - If the tool execution is **idempotent and cheap to replay** (pure function, < a few seconds, no external side effects), the correct design is to *not* offer resumption at all — issue no resume token, and on disconnect the client re-invokes with the same idempotency key. Resumption machinery is pure liability here. - If the tool execution is **long and side-effecting** (the case above), resumption is mandatory *and* the buffer must be either (a) pinned to a shard addressable by the token, or (b) externalized to a shared durable log (Redis stream, Kafka partition) so any shard can serve the resume. In-memory-per-shard buffers with fleet-wide HMAC and replicated sessions sit in the worst quadrant: they *look* resumable, pass every syntactic check, and fail only under rebalance. The specific trap: teams replicate the *session* (because cold-start amnesia is a known pain) and share the *signing key* (because key management is annoying), and each of those individually-reasonable choices removes one of the three validity conditions. Replicated session + shared key + local buffer = token travels, buffer doesn't. ## Operational Effect Once silent rebinding is possible, three second-order effects follow, each worse than the first: 1. **False completion propagates as ground truth.** A clean-close-on-empty is indistinguishable from a real finish, so the empty result enters the semantic memory / result store and is later retrieved as fact. The agent's episodic record now contains a completed task that never completed — a distillation-loss vector that no amount of downstream verification catches, because the record itself asserts success. 2. **Double execution on retry.** Because the client saw "complete," any supervisor-level retry policy fires against a task that is *still running* on the drained shard. Two executions append to the same session-keyed result store. Reconciliation requires an idempotency key the resume path never carried. 3. **Affinity drain becomes a correctness event, not an availability event.** Normally draining a shard is a latency blip. With silent rebinding, every in-flight resumable stream on that shard is a candidate for false completion, so deploys become data-corruption windows proportional to the number of long-running tasks — which is exactly the population resumable streams exist to protect. The guardrail that bounds all three is the same: **resume must fail closed with an explicit, typed error when buffer continuity cannot be proven, and the client must treat any resume response that does not begin at `last_event_seq + 1` within the same epoch as a hard abort requiring human/supervisor adjudication — never as completion.** Enforce it at both ends, because either end alone can be bypassed by a well-meaning "just close cleanly" handler. ```python import hashlib import hmac from dataclasses import dataclass class StreamContinuityError(RuntimeError): """Raised when a resume token cannot be proven to continue the same stream epoch.""" @dataclass(frozen=True) class ResumeToken: session_id: str stream_id: str last_event_seq: int epoch: str # execution epoch; changes if the tool is re-run from scratch owner_shard: str # the ONLY shard permitted to serve this resume def verify_resume( token: ResumeToken, presented_hmac: str, signing_key: bytes, local_shard: str, buffer_epoch: str | None, buffer_first_seq: int | None, buffer_last_seq: int | None, ) -> int: """Return the seq to resume from, or raise. Fails closed on every ambiguity. The three validity conditions are checked in order; any failure is a hard error, never an empty-success. """ expected = hmac.new( signing_key, f"{token.session_id}|{token.stream_id}|{token.last_event_seq}|{token.epoch}|{token.owner_shard}".encode(), hashlib.sha256, ).hexdigest() if not hmac.compare_digest(expected, presented_hmac): raise StreamContinuityError( f"resume token HMAC mismatch for stream {token.stream_id}; refusing to resume" ) # Condition 1: buffer locality. Only the owning shard may serve this stream. if local_shard != token.owner_shard: raise StreamContinuityError( f"stream {token.stream_id} is owned by shard {token.owner_shard}, " f"but resume landed on {local_shard}; rebinding would silently drop the buffer" ) # Condition 2: we must actually possess a buffer covering last_event_seq. if buffer_epoch is None or buffer_first_seq is None or buffer_last_seq is None: raise StreamContinuityError( f"no buffer present on owning shard for stream {token.stream_id}; " f"cannot prove contiguity at seq {token.last_event_seq}" ) # Condition 3: same execution epoch, and the requested offset is within the buffer. if buffer_epoch != token.epoch: raise StreamContinuityError( f"epoch mismatch for stream {token.stream_id}: token epoch {token.epoch}, " f"buffer epoch {buffer_epoch}; replay would splice two executions" ) if not (buffer_first_seq <= token.last_event_seq + 1 <= buffer_last_seq + 1): raise StreamContinuityError( f"requested resume seq {token.last_event_seq + 1} outside buffer range " f"[{buffer_first_seq}, {buffer_last_seq}] for stream {token.stream_id}" ) # Contiguity proven: the next emitted event MUST be exactly last_event_seq + 1. return token.last_event_seq + 1 def emit_resumed_stream(token: ResumeToken, events: list[tuple[int, str]], resume_seq: int): """Emit only from resume_seq; the first event must echo the identity witness.""" emitted = 0 for seq, payload in events: if seq < resume_seq: continue if emitted == 0 and seq != resume_seq: raise StreamContinuityError( f"first resumed event is seq {seq}, expected {resume_seq}; " f"client must abort, not treat as completion" ) emitted += 1 yield seq, payload if emitted == 0: # The cardinal sin: empty continuation closed as success. raise StreamContinuityError( f"resume produced zero events for stream {token.stream_id} at seq {resume_seq}; " f"closing cleanly here would be read as task completion" ) ```