# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-http-session-resumption-as-unsafe-after-a-backpressure-stall-and-how-does-the-resume-bound.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-http-session-resumption-as-unsafe-after-a-backpressure-stall-and-how-does-the-resume-bound.warrant.json
# Markdown SHA-256:   43ccd4afe46c99ba8bd217c7abffe1fd3b407721f4cdae2b6619f0a64f70ec4b
# Code AST SHA-256:   87f9321cccc369d7d186294a8fd38a05b99e78776e5540722142f8e106c95911
# Verified Classes:   ResumeBoundaryViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ResumeBoundaryViolation(RuntimeError):
    """Raised when an MCP streamable-HTTP resume would silently skip events."""
    pass


def verify_resume_safety(
    last_event_id: int,
    resume_floor_id: int | None,
    resumed_ids: list[int],
    announced_gaps: set[tuple[int, int]],
) -> None:
    """
    Decide whether a resume is a faithful continuation.
    Raises ResumeBoundaryViolation on any unrecoverable gap.
    """
    if resume_floor_id is None:
        raise ResumeBoundaryViolation(
            "server did not advertise resume_floor_id; "
            "resumption is unverifiable and must be treated as unsafe"
        )

    if last_event_id < resume_floor_id:
        # Backpressure evicted events the client never saw.
        raise ResumeBoundaryViolation(
            f"cursor {last_event_id} is below resume floor {resume_floor_id}; "
            f"events {last_event_id + 1}..{resume_floor_id - 1} are permanently lost"
        )

    # Verify the resumed stream is contiguous from the cursor, allowing only
    # explicitly announced gaps (coalescing under backpressure).
    expected = last_event_id + 1
    for eid in resumed_ids:
        if eid == expected:
            expected += 1
            continue
        if eid > expected:
            missing = (expected, eid - 1)
            if missing not in announced_gaps:
                raise ResumeBoundaryViolation(
                    f"unannounced gap {missing} in resumed stream; "
                    f"coalescing occurred without a gap record — stream is corrupt"
                )
            expected = eid + 1
        else:
            raise ResumeBoundaryViolation(
                f"non-monotonic event id {eid} after {expected - 1}; "
                f"server replay is inconsistent"
            )
