# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bind-resumption-state-when-an-mcp-streamable-http-session-reconnects-mid-sse-and-why-the-last-event-id-echo-is-not-sufficient.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bind-resumption-state-when-an-mcp-streamable-http-session-reconnects-mid-sse-and-why-the-last-event-id-echo-is-not-sufficient.warrant.json
# Markdown SHA-256:   c5b50a54f31a7242a24ffa0dce44f8c0903b0955cdd8de6198906913b2d9b10e
# Code AST SHA-256:   3afdb6fcc3e96d5a902849d5b46833bc9e87e7e38e5033b0f7bf67aaa07c0d9a
# Verified Classes:   ResumeInvariantViolation, StreamCursor, InstanceStreamState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class ResumeInvariantViolation(RuntimeError):
    """Raised when an instance attempts to resume an SSE stream without proof
    that its applied-state watermark is consistent with its replay cursor and
    that the cursor belongs to the current session epoch."""
    pass


@dataclass
class StreamCursor:
    epoch: str
    seq: int


@dataclass
class InstanceStreamState:
    # Durable, committed as a single unit: applied_seq is the watermark of
    # events fully applied to in-memory state; cursor_seq is what we echo as
    # Last-Event-ID. Invariant: applied_seq == cursor_seq after every commit.
    epoch: Optional[str] = None
    applied_seq: int = -1
    cursor_seq: int = -1
    committed_atomically: bool = False


def commit_event(state: InstanceStreamState, epoch: str, seq: int) -> None:
    """Apply-then-persist in one logical write. This is the commit point."""
    if state.epoch is not None and epoch != state.epoch:
        raise ResumeInvariantViolation(
            f"event epoch {epoch!r} != session epoch {state.epoch!r}; "
            "cannot apply foreign-epoch event"
        )
    if seq <= state.applied_seq:
        # Duplicate delivery: idempotent no-op, do not re-apply.
        return
    # ... apply event to in-memory state here ...
    state.epoch = epoch
    state.applied_seq = seq
    state.cursor_seq = seq
    state.committed_atomically = True


def plan_reconnect(
    state: InstanceStreamState,
    server_epoch: str,
    server_head_seq: int,
    replay_history_floor: int,
) -> str:
    """Decide between 'resume' and 'reconcile'. Returns the action taken.
    Raises ResumeInvariantViolation when neither path is safe."""
    if state.epoch is None:
        return "cold_start"

    if not state.committed_atomically:
        raise ResumeInvariantViolation(
            "cursor and applied-state watermark were not committed atomically; "
            "resume would risk silent gap or duplicate application"
        )

    if state.applied_seq != state.cursor_seq:
        raise ResumeInvariantViolation(
            f"watermark {state.applied_seq} != cursor {state.cursor_seq}; "
            "refusing to echo Last-Event-ID that leads applied state"
        )

    if server_epoch != state.epoch:
        # Session expired / rebalanced to a new backend. ID space is different;
        # resuming would replay foreign events or skip a gap. Force reconcile.
        return "reconcile"

    if state.cursor_seq < replay_history_floor:
        # Server can no longer replay from our cursor; a gap is unavoidable.
        # Do not pretend to resume.
        return "reconcile"

    if state.cursor_seq > server_head_seq:
        raise ResumeInvariantViolation(
            f"cursor {state.cursor_seq} ahead of server head {server_head_seq}; "
            "state and server have diverged"
        )

    return "resume"


def reconnect(
    state: InstanceStreamState,
    server_epoch: str,
    server_head_seq: int,
    replay_history_floor: int,
) -> str:
    action = plan_reconnect(state, server_epoch, server_head_seq, replay_history_floor)
    if action == "resume":
        # Safe: echo Last-Event-ID = state.cursor_seq, replay strictly after it.
        return f"GET /mcp Last-Event-ID: {state.cursor_seq}"
    if action == "reconcile":
        # Re-establish session, re-fetch tools/resources, treat old stream advisory.
        state.epoch = server_epoch
        state.applied_seq = server_head_seq
        state.cursor_seq = server_head_seq
        state.committed_atomically = True
        return "POST /mcp initialize + tools/list + resources/list"
    return "POST /mcp initialize"


# --- exercise the failure trace from the record ---
s = InstanceStreamState(epoch="e1", applied_seq=1041, cursor_seq=1042,
                        committed_atomically=True)
try:
    reconnect(s, server_epoch="e1", server_head_seq=1050, replay_history_floor=1000)
except ResumeInvariantViolation as e:
    # watermark(1041) != cursor(1042): the exact seam bug from the trace.
    print("blocked:", e)

# epoch change after rebalance must reconcile, not resume across ID spaces:
s2 = InstanceStreamState(epoch="e1", applied_seq=1042, cursor_seq=1042,
                         committed_atomically=True)
print(reconnect(s2, server_epoch="e2", server_head_seq=3, replay_history_floor=0))
