# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-tool-call-replay-divergence-when-an-mcp-stream-is-resumed-across-an-http-session-re-bind.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-tool-call-replay-divergence-when-an-mcp-stream-is-resumed-across-an-http-session-re-bind.warrant.json
# Markdown SHA-256:   cc939654d701918d7c379a8e1668439240d62b628ba76a92488848aa5ab84c12
# Code AST SHA-256:   d9afa068d877e8527f99f8b6543d245178722faf5c8accc7a25ed63ca034a5ec
# Verified Classes:   SessionCursorMismatch, ReplayBuffer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SessionCursorMismatch(RuntimeError):
    """Raised when a Last-Event-ID cursor cannot be proven to belong to the
    presented Mcp-Session-Id, so resumption would risk replay divergence."""
    pass


class ReplayBuffer:
    def __init__(self):
        # session_id -> list of (seq, event_payload)
        self._buffers: dict[str, list[tuple[int, dict]]] = {}

    def mint_cursor(self, session_id: str, seq: int) -> str:
        # Cursor is scoped: wire form encodes session so it can be validated.
        return f"{session_id}:{seq}"

    def resume(self, session_id: str, last_event_id: str) -> list[dict]:
        try:
            cursor_session, cursor_seq_str = last_event_id.rsplit(":", 1)
            cursor_seq = int(cursor_seq_str)
        except (ValueError, AttributeError):
            raise SessionCursorMismatch(
                f"malformed cursor {last_event_id!r}; refusing to resume"
            )

        # Invariant: cursor must have been minted by the same session buffer.
        if cursor_session != session_id:
            raise SessionCursorMismatch(
                f"cursor {last_event_id!r} belongs to session {cursor_session!r} "
                f"but request is bound to {session_id!r}; replay would diverge"
            )

        buf = self._buffers.get(session_id)
        if buf is None:
            raise SessionCursorMismatch(
                f"session {session_id!r} buffer is gone; cursor {last_event_id!r} "
                f"is unverifiable, must re-issue with idempotency key"
            )

        # Monotonic cut: only events strictly after the cursor are replayed.
        return [payload for seq, payload in buf if seq > cursor_seq]
