# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-mcp-streamable-http-backpressure-as-a-resumable-checkpoint-rather-than-a-lost-call.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-mcp-streamable-http-backpressure-as-a-resumable-checkpoint-rather-than-a-lost-call.warrant.json
# Markdown SHA-256:   a304041c38bf2291d5b2cf1701bccc7d3ad886a20e4148c4860ba9f56eb5e5ba
# Code AST SHA-256:   2563379521b0179320b427250854a48bfcbd287da15abe83c229c8367625b854
# Verified Classes:   McpResumeGapError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class McpResumeGapError(RuntimeError):
    """Raised when a streamable-HTTP MCP resume would cross a silent replay-buffer gap."""
    def __init__(self, last_committed_id: int, ring_floor: int | None):
        self.last_committed_id = last_committed_id
        self.ring_floor = ring_floor
        super().__init__(
            f"resume unsafe: committed={last_committed_id} floor={ring_floor} "
            f"missing={None if ring_floor is None else ring_floor - last_committed_id - 1} frames"
        )


def resume_streamable_http(
    last_committed_id: int,
    ring_floor: int | None,
    *,
    allow_restart: bool,
    idempotency_key: str | None,
) -> str:
    # No floor disclosed: cannot prove prefix relation, must fail closed.
    if ring_floor is None:
        if not allow_restart or idempotency_key is None:
            raise McpResumeGapError(last_committed_id, None)
        return "restart"

    # Committed watermark is behind the oldest retained event: lossy resume.
    if last_committed_id < ring_floor:
        if not allow_restart or idempotency_key is None:
            raise McpResumeGapError(last_committed_id, ring_floor)
        return "restart"

    # Committed watermark is inside the retained window: safe to replay.
    return "resume"
