# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-resumable-mcp-stream-is-actually-unrecoverable-silent-event-id-discontinuity-across-http-native-transport-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-resumable-mcp-stream-is-actually-unrecoverable-silent-event-id-discontinuity-across-http-native-transport-reconnect.warrant.json
# Markdown SHA-256:   35dff6f35c4fd3ba562f4b500b116e20d351e9ff719524e75edf5d6c592df669
# Code AST SHA-256:   b9c01fc7581366b99e8939cdf2837392195228e63a4e2e53e292303b029e75f6
# Verified Classes:   StreamResumptionError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class StreamResumptionError(RuntimeError):
    """Raised when a resumed MCP HTTP-native stream is not a valid continuation."""
    pass


def validate_resumption(
    last_event_id: int,
    first_replayed_id: int | None,
    replayed_event_ids: list[int],
    awaited_terminal_seen: bool,
    same_backend: bool,
) -> None:
    """
    Enforce the resumption invariant for an SSE reconnect carrying Last-Event-ID.

    Raises StreamResumptionError if the resumed stream cannot be trusted as a
    continuation of the original logical stream.
    """
    if not same_backend:
        raise StreamResumptionError(
            "session id stable but backend changed; event log not durable across replicas"
        )

    if first_replayed_id is None:
        raise StreamResumptionError(
            f"resume with Last-Event-ID={last_event_id} produced no replayed events"
        )

    if first_replayed_id <= last_event_id:
        raise StreamResumptionError(
            f"event-ID regression: last seen {last_event_id}, replay started at "
            f"{first_replayed_id}; server log was reset, not resumed"
        )

    if first_replayed_id != last_event_id + 1:
        raise StreamResumptionError(
            f"event-ID gap: expected successor {last_event_id + 1}, got "
            f"{first_replayed_id}; events in between are lost"
        )

    for prev, cur in zip(replayed_event_ids, replayed_event_ids[1:]):
        if cur != prev + 1:
            raise StreamResumptionError(
                f"non-contiguous replay: {prev} -> {cur}; buffer truncated mid-stream"
            )

    if not awaited_terminal_seen:
        raise StreamResumptionError(
            "replayed stream closed without the awaited terminal event and without "
            "an error signal; replay is a strict subset of required events"
        )
