# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-event-stream-truncation-when-an-mcp-http-transport-resumes-a-stateless-tool-call-from-a-stale-last-event-id.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-event-stream-truncation-when-an-mcp-http-transport-resumes-a-stateless-tool-call-from-a-stale-last-event-id.warrant.json
# Markdown SHA-256:   5419f4e30525b15a94ede22db18af7f62acc1a3ce839565fce2e689dc56e4a26
# Code AST SHA-256:   23c813b8d25798dc7adc2736db04c0a187998fa3cfd444a3a3f3bc4792518bd0
# Verified Classes:   StreamDiscontinuityError, ResumeDecision
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class StreamDiscontinuityError(RuntimeError):
    """Raised when a resumed MCP SSE stream does not continue the requested event ID."""


@dataclass(frozen=True)
class ResumeDecision:
    requested_last_event_id: int
    first_delivered_id: int
    contiguous: bool


def verify_resume_continuity(
    requested_last_event_id: int,
    first_delivered_id: int,
    *,
    id_space_contiguous: bool = True,
    explicit_gap_signalled: bool = False,
) -> ResumeDecision:
    """
    Enforce the resume invariant for stateless MCP tool calls.

    A resume is valid only if the first delivered id is the exact successor of the
    requested Last-Event-ID, or the server explicitly signalled a gap. Any forward
    jump, backward reset, or non-successor id is a logical discontinuity and MUST
    abort the call rather than merge the stream.
    """
    if explicit_gap_signalled:
        return ResumeDecision(requested_last_event_id, first_delivered_id, contiguous=False)

    if id_space_contiguous:
        expected = requested_last_event_id + 1
        if first_delivered_id != expected:
            raise StreamDiscontinuityError(
                f"resume discontinuity: requested Last-Event-ID={requested_last_event_id}, "
                f"expected first id={expected}, got {first_delivered_id}; "
                f"event log likely evicted or worker recycled — abort and restart stateless call"
            )
    else:
        # Non-contiguous ID space: only a strictly forward move is acceptable.
        if first_delivered_id <= requested_last_event_id:
            raise StreamDiscontinuityError(
                f"resume regression: requested Last-Event-ID={requested_last_event_id}, "
                f"first id={first_delivered_id} is not strictly greater; stream reset detected"
            )

    return ResumeDecision(requested_last_event_id, first_delivered_id, contiguous=True)


def resume_stateless_tool_call(
    requested_last_event_id: int,
    first_delivered_id: int,
    *,
    id_space_contiguous: bool = True,
    explicit_gap_signalled: bool = False,
) -> ResumeDecision:
    decision = verify_resume_continuity(
        requested_last_event_id,
        first_delivered_id,
        id_space_contiguous=id_space_contiguous,
        explicit_gap_signalled=explicit_gap_signalled,
    )
    if not decision.contiguous:
        # Explicit gap: discard stream and restart the stateless invocation.
        raise StreamDiscontinuityError(
            f"explicit gap signalled between {requested_last_event_id} and "
            f"{first_delivered_id}; restarting stateless tool call"
        )
    return decision
