# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-resumable-session-replay-as-unsafe-across-a-transport-upgrade-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-resumable-session-replay-as-unsafe-across-a-transport-upgrade-boundary.warrant.json
# Markdown SHA-256:   43edf8284beeee1ac116b2b35f9c4ab2ccb11772fe1c00f5df3a920588f8fe46
# Code AST SHA-256:   2c4065ba90932435471d68b48dd32c9b7c3695f83cc75cd86f69a167e78d2ef3
# Verified Classes:   UnsafeResumptionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnsafeResumptionError(RuntimeError):
    """Raised when an MCP resumable-session replay cannot be proven gap-free."""
    pass


def validate_resumption(
    cursor_event_id: int,
    first_replayed_event_id: int,
    session_incarnation: str,
    current_incarnation: str,
    globally_monotonic: bool,
) -> None:
    """
    Gate an MCP SSE resumption request. Raises if the replay cannot be
    proven to have skipped zero events. Returns None only when safe.
    """
    if session_incarnation != current_incarnation and not globally_monotonic:
        # Fresh process owns a mirrored logical session but cannot see the
        # original event log. Gap detection is impossible; refuse.
        raise UnsafeResumptionError(
            f"session owned by incarnation {session_incarnation!r}, "
            f"serviced by {current_incarnation!r}; no shared monotonic log"
        )

    if not globally_monotonic:
        # Even same-incarnation resumption is only safe if the process
        # still holds the log and can assert successor ordering.
        raise UnsafeResumptionError(
            "non-monotonic event IDs: cannot prove absence of events "
            f"between cursor {cursor_event_id} and replay {first_replayed_event_id}"
        )

    if first_replayed_event_id != cursor_event_id + 1:
        # Accepted cursor but non-successor first event: silent gap or
        # counter reset. Caller must reconcile application state instead.
        raise UnsafeResumptionError(
            f"cursor {cursor_event_id} but replay started at "
            f"{first_replayed_event_id}; gap or ID reuse detected"
        )
