# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-resumability-invariant-in-mcp-http-native-streaming-when-last-event-id-replay-collides-with-backpressure-ind.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-resumability-invariant-in-mcp-http-native-streaming-when-last-event-id-replay-collides-with-backpressure-ind.warrant.json
# Markdown SHA-256:   02a3de8a56de0a52350892464faf7897957139c589a727487e75febd1998379f
# Code AST SHA-256:   704b73a9149fbccdd32e871d66257dd5e904900dc1f11b7f4742b4d70933cccd
# Verified Classes:   ResumeGapError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ResumeGapError(RuntimeError):
    """Raised when an MCP HTTP-native stream resume cannot reconstruct the
    exact event sequence: either the server evicted unacknowledged events
    (server-side gap) or the client's assembled payload disagrees with the
    tool's declared output size (client-side gap)."""
    pass


def resume_session(last_event_id: int, min_retained_id: int) -> None:
    # Server-side invariant: replay is only valid if the client's last
    # acknowledged id is still at or above the retention floor. If the
    # server evicted events while the id counter kept advancing, the
    # floor has moved past the client and the gap is unrecoverable.
    if last_event_id < min_retained_id - 1:
        raise ResumeGapError(
            f"resume gap: client at {last_event_id}, "
            f"server retention floor {min_retained_id}; "
            f"events {last_event_id + 1}..{min_retained_id - 1} were evicted "
            f"under backpressure and cannot be replayed"
        )


def finalize_stream(declared_bytes: int, received_bytes: int) -> None:
    # Client-side invariant: a contiguous id sequence is not proof of
    # continuity. The only reliable cross-check is the tool's declared
    # output size versus what the stream actually delivered.
    if received_bytes != declared_bytes:
        raise ResumeGapError(
            f"stream discontinuity: tool declared {declared_bytes} bytes, "
            f"received {received_bytes}; interior eviction suspected, "
            f"re-invoke tool rather than resume"
        )


def handle_reconnect(session, last_event_id: int) -> None:
    resume_session(last_event_id, session.min_retained_id)
    finalize_stream(session.declared_bytes, session.received_bytes)
