# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-and-the-server-s-push-queue-has-already-been-drained-by-a-sibling-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-and-the-server-s-push-queue-has-already-been-drained-by-a-sibling-reconnect.warrant.json
# Markdown SHA-256:   0bb8e0e01dfbbf49827d24d019738956e37c7dff02df0566e552f459cb8a041f
# Code AST SHA-256:   d9fc580f06923ff9057f907e91707d3b6b9dca9e42215361942cf54140ce40f6
# Verified Classes:   StreamResumeGapError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StreamResumeGapError(RuntimeError):
    """Raised when an MCP HTTP stream resumes behind the server drain watermark.

    A behind-watermark resume means the server will NOT replay events between
    last_seen_id and the watermark, and will emit no gap signal unless the
    server implements the resume_gap control frame. The client MUST NOT resume
    reasoning on this session until a full resync (tools/list, resources re-read,
    in-flight call status poll) has completed, because lost push notifications
    may include tool-schema changes and terminal progress events.
    """


def resume_stream(
    last_seen_id: int,
    server_watermark: int,
    *,
    gap_signal_received: bool,
    replayed_from: int | None,
) -> int:
    """Validate cursor continuity on reconnect and return the first live event id.

    Contract:
      - If the server sent an explicit resume_gap frame, the caller must run
        the resync protocol before consuming live events; we return the live
        cursor but the caller is responsible for invalidation.
      - If replayed_from is None (nothing to replay) AND last_seen_id is behind
        the watermark AND no gap signal was sent, this is the silent-skip case:
        raise, do not proceed.
      - If replayed_from == last_seen_id + 1, continuity holds; safe to proceed.
    """
    if replayed_from is not None and replayed_from == last_seen_id + 1:
        # Clean continuity: no events were skipped.
        return replayed_from

    behind = last_seen_id < server_watermark
    skipped = server_watermark - last_seen_id

    if behind and not gap_signal_received:
        # The dangerous case: server drained events [last_seen_id+1 .. watermark]
        # to a sibling connection and will not replay them. No error frame.
        raise StreamResumeGapError(
            f"Silent resume gap: last_seen_id={last_seen_id} "
            f"< watermark={server_watermark}; {skipped} events unreplayed "
            f"and no resume_gap frame received. Refusing to resume reasoning; "
            f"run full resync (tools/list, resources re-read, in-flight poll)."
        )

    if behind and gap_signal_received:
        # Server was honest about the gap. Caller must resync before reasoning.
        # We surface the live cursor but the caller is obligated to invalidate.
        return server_watermark + 1

    # Not behind the watermark: either caught up or ahead (shouldn't happen;
    # treat as a protocol violation rather than guessing).
    if last_seen_id > server_watermark:
        raise StreamResumeGapError(
            f"Cursor ahead of server watermark: last_seen_id={last_seen_id} "
            f"> watermark={server_watermark}. Server state was reset or "
            f"session ID reused across epochs; abandon session and re-init."
        )
    return last_seen_id + 1
