# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-session-resumption-token-has-been-silently-rebound-to-a-divergent-event-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-session-resumption-token-has-been-silently-rebound-to-a-divergent-event-stream.warrant.json
# Markdown SHA-256:   3d8d0af5753963b41308cf58bb3dcde1d0b4b172ab83455d7dbd432ffc5a4d26
# Code AST SHA-256:   10b9198aaacf9938e60261a9da9a0472216146f54774812a882b601f5235d68f
# Verified Classes:   ResumptionAmbiguityError, Event, SessionState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Literal


class ResumptionAmbiguityError(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot be proven to be a
    prefix-composable continuation of the pre-drop event log."""


@dataclass
class Event:
    id: int
    kind: Literal["progress", "result", "error", "delta"]
    progress_token: str | None = None
    coalesced: bool = False


@dataclass
class SessionState:
    session_id: str
    last_event_id: int = 0
    open_tokens: set[str] = field(default_factory=set)


def reconcile_resume(state: SessionState, resumed: list[Event]) -> None:
    """Validate that a resumed stream is a faithful continuation.

    Invariant: every token open at drop time must be resolved by exactly one
    terminal event (result/error) at an id strictly greater than last_event_id,
    OR remain open, OR be accompanied by an explicit coalescing marker.
    Contiguous ids alone are NOT sufficient.
    """
    if not resumed:
        return

    first = resumed[0]
    if first.id <= state.last_event_id:
        raise ResumptionAmbiguityError(
            f"resumed stream first id {first.id} is not past "
            f"Last-Event-ID {state.last_event_id}; server may be replaying "
            f"stale state under a new connection"
        )

    if first.id > state.last_event_id + 1 and not first.coalesced:
        raise ResumptionAmbiguityError(
            f"gap detected: expected id {state.last_event_id + 1}, "
            f"got {first.id} with no coalescing marker; "
            f"intermediate events were dropped without disclosure"
        )

    resolved: set[str] = set()
    for ev in resumed:
        if ev.kind in ("result", "error") and ev.progress_token is not None:
            if ev.progress_token in state.open_tokens and not ev.coalesced:
                raise ResumptionAmbiguityError(
                    f"token {ev.progress_token!r} was open at drop time but "
                    f"resumed stream delivers terminal {ev.kind!r} at id "
                    f"{ev.id} with no coalescing marker; outcome is unknown "
                    f"and re-issuance must be idempotent or explicitly cancelled"
                )
            resolved.add(ev.progress_token)

    for tok in state.open_tokens - resolved:
        # Token still open after resume: legal, but the client must not
        # re-issue the originating tools/call.
        continue

    state.last_event_id = resumed[-1].id
    state.open_tokens -= resolved


def resume_stream(state: SessionState, resumed: list[Event]) -> None:
    try:
        reconcile_resume(state, resumed)
    except ResumptionAmbiguityError:
        # Fail closed: caller must re-establish a fresh session or issue
        # an idempotent retry keyed on the original progress token.
        raise
