# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-resumption-as-unsafe-after-a-last-event-id-gap-and-how-does-backpressure-collapse.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-resumption-as-unsafe-after-a-last-event-id-gap-and-how-does-backpressure-collapse.warrant.json
# Markdown SHA-256:   592c40dd41047a768a3759bce4450b42d0fe685eb2b9e1cf0f8ec6e264ca5c84
# Code AST SHA-256:   7275d9e2cd0f03345e6426ba80c4994203c9de4aa6b0bb0508960aa14a778a03
# Verified Classes:   SilentResumeGapError, ResumeResult, StreamCursor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class SilentResumeGapError(RuntimeError):
    """Raised when an MCP streamable-HTTP resume returns a 200 whose first
    replayed SSE id does not equal last_consumed_id + 1, with no explicit
    gap marker. The stream is live and well-formed, which is exactly why
    it is unsafe: continuity is assumed but not honored."""


@dataclass
class ResumeResult:
    status: int
    first_replayed_id: int | None
    explicit_gap: bool          # server sent event: resume-gap / 409
    oldest_retained_id: int | None


@dataclass
class StreamCursor:
    last_consumed_id: int = 0
    durable_checkpoint_id: int = 0
    # events between checkpoint and head that the agent cannot re-derive
    uncheckpointed_span: list[int] = field(default_factory=list)


def verify_resume(cursor: StreamCursor, result: ResumeResult) -> None:
    """Enforce the contiguity invariant before feeding the stream back
    into the reasoning loop. Raises on silent gap; returns on safe resume."""
    if result.status == 409 or result.explicit_gap:
        # Bounded, detectable failure. Agent may rehydrate from checkpoint.
        if cursor.durable_checkpoint_id < cursor.last_consumed_id:
            raise SilentResumeGapError(
                f"explicit gap at id={cursor.last_consumed_id}; "
                f"checkpoint id={cursor.durable_checkpoint_id} is behind "
                f"consumed head; uncheckpointed span "
                f"{cursor.uncheckpointed_span} cannot be re-derived"
            )
        return

    if result.status != 200:
        raise SilentResumeGapError(f"unexpected resume status {result.status}")

    expected = cursor.last_consumed_id + 1
    if result.first_replayed_id != expected:
        # This is the silent-gap case: 200 OK, no marker, wrong head.
        raise SilentResumeGapError(
            f"silent resume gap: expected first id {expected}, "
            f"server replayed from {result.first_replayed_id} "
            f"(oldest retained {result.oldest_retained_id}); "
            f"events {expected}..{result.first_replayed_id - 1} are lost"
        )


def resume_session(cursor: StreamCursor, reconnect_fn) -> None:
    """Reconnect and only advance state if the resume is provably contiguous."""
    result = reconnect_fn(last_event_id=cursor.last_consumed_id)
    verify_resume(cursor, result)
    # Safe: stream is a faithful continuation of the consumed prefix.
    cursor.durable_checkpoint_id = cursor.last_consumed_id
    cursor.uncheckpointed_span.clear()
