# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-preserve-mcp-sse-resumption-cursors-across-a-mid-stream-transport-upgrade.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-preserve-mcp-sse-resumption-cursors-across-a-mid-stream-transport-upgrade.warrant.json
# Markdown SHA-256:   eb2be143eef43120f6476c4a66251109bd0f1f69221ba3d113d6a6e51595f1af
# Code AST SHA-256:   109da6904aec6d854bb83e16ec77070488920fb45e287c709548608fa6d2d7d5
# Verified Classes:   CursorHandoffError, UpgradeProposal
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class CursorHandoffError(RuntimeError):
    """Raised when an MCP SSE-to-WebSocket upgrade cannot preserve cursor continuity."""
    pass


class UpgradeProposal:
    def __init__(self, control_event_id: int, resume_from: int, handoff_token: str | None):
        self.control_event_id = control_event_id
        self.resume_from = resume_from
        self.handoff_token = handoff_token


def negotiate_upgrade(
    proposal: UpgradeProposal,
    last_applied_event_id: int,
    durable_cursor_written: bool,
) -> dict:
    # The upgrade is only safe if the client can prove what it has consumed
    # and the server has offered a binding into the WebSocket cursor namespace.
    if proposal.handoff_token is None:
        raise CursorHandoffError(
            f"upgrade at event {proposal.control_event_id} carries no handoff binding; "
            "refusing to migrate cursor namespace"
        )
    if not durable_cursor_written:
        raise CursorHandoffError(
            f"last_applied={last_applied_event_id} not durably checkpointed; "
            "upgrade could race a resume and re-deliver applied events"
        )
    if last_applied_event_id > proposal.control_event_id:
        raise CursorHandoffError(
            f"last_applied={last_applied_event_id} is ahead of control event "
            f"{proposal.control_event_id}; cursor is already suspect, aborting"
        )
    return {
        "type": "resume",
        "handoff_token": proposal.handoff_token,
        "last_event_id": last_applied_event_id,
        "expected_cursor": proposal.resume_from,
    }


def verify_resume_ack(ack: dict, expected_cursor: int, last_applied_event_id: int) -> None:
    # The ack must either confirm the expected cursor or announce a replay
    # covering the gap. Anything else is an unverifiable seam.
    ack_cursor = ack.get("cursor")
    replay_range = ack.get("replay_range")  # (start, end) inclusive, or None
    if ack_cursor == expected_cursor:
        return
    if replay_range is not None:
        start, end = replay_range
        if start <= last_applied_event_id + 1 and end >= expected_cursor - 1:
            return
        raise CursorHandoffError(
            f"replay range {replay_range} does not cover gap "
            f"({last_applied_event_id + 1}..{expected_cursor - 1})"
        )
    raise CursorHandoffError(
        f"resume_ack cursor={ack_cursor} unverifiable against expected={expected_cursor}; "
        "aborting stream to avoid silent divergence"
    )
