# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-the-last-event-id-cursor-against-a-server-side-replay-window-when-resuming-an-mcp-http-native-streaming-session.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-the-last-event-id-cursor-against-a-server-side-replay-window-when-resuming-an-mcp-http-native-streaming-session.warrant.json
# Markdown SHA-256:   43373242aca5cd08d33e06610afd4b996f65b98cbf5ce7bde086c742cf116f68
# Code AST SHA-256:   a3d96388278414acf4838508157fa4807aa108655c481834dd42cae72a494d27
# Verified Classes:   McpResumeInvariantError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class McpResumeInvariantError(RuntimeError):
    """Raised when a resuming MCP client cannot prove its cursor is inside the server replay window."""
    pass


def resume_stream(
    applied_cursor: int,
    window_floor: int,
    original_idempotency_token: str,
    retry_idempotency_token: str,
    gap_disclosure_supported: bool,
) -> int:
    """Return the event ID from which the server should replay.

    Enforces the three-condition validity check before any replay is applied.
    """
    if applied_cursor < window_floor - 1:
        if not gap_disclosure_supported:
            raise McpResumeInvariantError(
                f"cursor {applied_cursor} below window floor {window_floor} "
                f"and server does not disclose evicted range; "
                f"gap {applied_cursor + 1}..{window_floor - 1} is unobservable"
            )
        # Gap is disclosable: caller must decide whether missing events are load-bearing.
        raise McpResumeInvariantError(
            f"cursor {applied_cursor} below window floor {window_floor}; "
            f"evicted range {applied_cursor + 1}..{window_floor - 1} must be "
            f"inspected before resume is safe"
        )

    if original_idempotency_token != retry_idempotency_token:
        raise McpResumeInvariantError(
            "retry idempotency token differs from original; "
            "concurrent execution cannot be deduplicated and replayed "
            "result may be a second execution, not a continuation"
        )

    return applied_cursor
