# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-sse-resumption-tokens-from-silently-forking-an-mcp-session-across-reconnects.md # Remnant Warrant: https://corpusfetch.com/c/which-invariants-prevent-sse-resumption-tokens-from-silently-forking-an-mcp-session-across-reconnects.warrant.json # Markdown SHA-256: bce63f864b8127995733c7010e9cca07b5273223fca386707a2729ed4582c4db # Code AST SHA-256: 071597ee908ec11fc8ad07ad078f78ed9f71abed36cce282321ca0ef7f8de9d6 # Verified Classes: UnsafeResumptionError, InFlightRequest, SessionState # Defensive Guards: 4 fail-closed invariants (zero external deps) # Governance: Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com) from dataclasses import dataclass, field from typing import Optional class UnsafeResumptionError(RuntimeError): """Raised when a resumption token would replay past lost in-flight state.""" @dataclass class InFlightRequest: request_id: str dispatch_seq: int idempotent: bool terminal_seq: Optional[int] = None @dataclass class SessionState: session_id: str buffer_tail_seq: int requests: dict[str, InFlightRequest] = field(default_factory=dict) def reconcile_resumption( session: SessionState, last_event_id: int, client_dedupe_window_s: float, server_buffer_ttl_s: float, ) -> int: """ Validate a resume token against durable session state before replay. Returns the sequence number to replay from. Raises if unsafe. """ if last_event_id > session.buffer_tail_seq: raise UnsafeResumptionError( f"token {last_event_id} ahead of buffer tail {session.buffer_tail_seq}" ) if client_dedupe_window_s < server_buffer_ttl_s: raise UnsafeResumptionError( f"client dedupe {client_dedupe_window_s}s shorter than server " f"buffer TTL {server_buffer_ttl_s}s; re-dispatch reachable" ) for req in session.requests.values(): if req.dispatch_seq > last_event_id: continue # dispatched after the token; not yet replayed if req.terminal_seq is not None and req.terminal_seq <= last_event_id: continue # already delivered before the token; safe # In-flight at or before the token with no terminal event in range. if not req.idempotent: raise UnsafeResumptionError( f"non-idempotent request {req.request_id} in flight since " f"seq {req.dispatch_seq}, no terminal event <= {last_event_id}; " f"refusing resume, require fresh negotiation" ) # Idempotent: replay is safe, but caller must dedupe by id. return last_event_id + 1 def handle_resume(session: SessionState, last_event_id: int, **kw) -> int: try: return reconcile_resumption(session, last_event_id, **kw) except UnsafeResumptionError: # Surface as a non-retryable session-invalid to the client. session.requests.clear() raise