# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-session-after-a-transport-level-backpressure-stall-but-the-server-has-already-advanced-the-ses.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-session-after-a-transport-level-backpressure-stall-but-the-server-has-already-advanced-the-ses.warrant.json
# Markdown SHA-256:   95101dd16803b00cb5817749fec149854587a08af46ba35c15c1dfc3807e0c65
# Code AST SHA-256:   ac5ef07c71df95633520afbf6a0b5c146b723e27313ad67cb12ff175d5738c6c
# Verified Classes:   ResumptionContinuityError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ResumptionContinuityError(RuntimeError):
    """Raised when a resumed MCP streamable session delivers an event that
    does not continue the client's durably-applied cursor. Must never be
    swallowed as a duplicate — a gap and a duplicate are indistinguishable
    without the server's retained_from sentinel, and treating a gap as a
    duplicate silently corrupts downstream agent state."""


def apply_resumed_event(
    event: dict,
    last_applied_id: int | None,
    server_retained_from: int | None,
) -> int:
    event_id = event["id"]

    # Server-declared gap: replay began after our cursor was evicted.
    if server_retained_from is not None and last_applied_id is not None:
        if server_retained_from > last_applied_id + 1:
            raise ResumptionContinuityError(
                f"server evicted events in ({last_applied_id}, {server_retained_from}); "
                f"replay cannot reconstruct the gap — re-initialize session"
            )

    # Client-side contiguity assertion. A non-consecutive ID after resumption
    # is a gap, not a duplicate. Refuse to merge.
    if last_applied_id is not None and event_id != last_applied_id + 1:
        raise ResumptionContinuityError(
            f"non-contiguous event: expected id {last_applied_id + 1}, got {event_id}; "
            f"applying it would fabricate a contiguous history from a truncated stream"
        )

    return event_id
