# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-mcp-session-resumption-is-unsafe-after-partial-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-mcp-session-resumption-is-unsafe-after-partial-failure.warrant.json
# Markdown SHA-256:   62bf69e88e2a0186baf33a30af17cfbe6cb6f623947b2d52e37bf8a7d044eb27
# Code AST SHA-256:   807466cc2d29e8c89cf581b8bd8769aa31f25ca3b71d0f122789e65945c3ff14
# Verified Classes:   UnsafeResumeError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UnsafeResumeError(RuntimeError):
    """Raised when a replayed MCP event stream is not contiguous with the
    last durably committed event id. Accepting such a stream risks
    duplicate side-effecting tool calls."""
    pass


def verify_resume_contiguity(last_committed_id: int, first_replayed_event: dict) -> None:
    """Enforce the safe-resumption invariant before accepting a replayed stream.

    first_replayed_event is the parsed first SSE frame after reconnect, e.g.
    {"id": "42", "event": "message", "data": "..."} or {"event": "message", ...}.
    """
    raw_id = first_replayed_event.get("id")
    if raw_id is None:
        # Missing id: Last-Event-ID is meaningless on the next reconnect.
        raise UnsafeResumeError(
            "replayed event has no 'id' field; cannot establish contiguity"
        )

    try:
        first_id = int(raw_id)
    except (TypeError, ValueError):
        raise UnsafeResumeError(f"non-integer event id {raw_id!r}; refusing resume")

    expected = last_committed_id + 1
    if first_id == expected:
        return  # contiguous: safe to accept
    if first_id <= last_committed_id:
        raise UnsafeResumeError(
            f"replay/gap ambiguity: first_id={first_id} <= "
            f"last_committed={last_committed_id}; server likely lost its event log"
        )
    # first_id > expected
    raise UnsafeResumeError(
        f"gap detected: first_id={first_id} > expected={expected}; "
        f"events were dropped between reconnect attempts"
    )
