# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-streamable-session-resumption-as-invalid-and-how-does-a-silent-event-id-gap-corrupt-agent-state-co.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-streamable-session-resumption-as-invalid-and-how-does-a-silent-event-id-gap-corrupt-agent-state-co.warrant.json
# Markdown SHA-256:   edfec9253d9bcc05485d086a37d7dbfe9c4bb329e29bd39171e8c089574a2510
# Code AST SHA-256:   9e921c3a3fed4027c940bbdf3dac9bb7d96e14813ecc7e67478b41800b868570
# Verified Classes:   ResumptionGapError, StreamState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ResumptionGapError(RuntimeError):
    """Raised when an MCP streamable-session resumption cannot prove event-level continuity."""
    pass


@dataclass
class StreamState:
    session_epoch: str
    last_event_id: int
    pending_artifact: Optional[str] = None
    superseded: bool = False


def resume_stream(
    state: StreamState,
    *,
    server_epoch: str,
    first_replayed_id: int,
    subsequent_ids: list[int],
    result_artifact: Optional[str],
) -> StreamState:
    # 1. Identity proof: server epoch must match the session we believe we are in.
    if server_epoch != state.session_epoch:
        raise ResumptionGapError(
            f"session epoch changed {state.session_epoch!r} -> {server_epoch!r}; "
            f"cannot resume, must re-initialize and re-query authoritative state"
        )

    # 2. Residency proof: first replayed event must be exactly last+1.
    if first_replayed_id != state.last_event_id + 1:
        raise ResumptionGapError(
            f"resume gap: expected first event {state.last_event_id + 1}, "
            f"got {first_replayed_id}; server buffer no longer holds Last-Event-ID "
            f"{state.last_event_id} — silent data loss window"
        )

    # 3. Contiguity proof: no integer may be skipped in the replayed sequence.
    expected = first_replayed_id
    for eid in subsequent_ids:
        if eid != expected + 1:
            raise ResumptionGapError(
                f"non-contiguous event stream: {expected} -> {eid}; "
                f"missing {eid - expected - 1} event(s), possible superseded/cancel signal lost"
            )
        expected = eid

    # Only now may we advance the world model.
    new_state = StreamState(
        session_epoch=server_epoch,
        last_event_id=expected,
        pending_artifact=result_artifact if not state.superseded else None,
        superseded=state.superseded,
    )
    return new_state


def handle_superseded(state: StreamState) -> StreamState:
    # Called only when a superseded event was actually delivered.
    return StreamState(
        session_epoch=state.session_epoch,
        last_event_id=state.last_event_id,
        pending_artifact=None,
        superseded=True,
    )
