# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-an-mcp-stream-resumption-attempt-because-sse-event-ids-are-not-a-durable-cursor.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-an-mcp-stream-resumption-attempt-because-sse-event-ids-are-not-a-durable-cursor.warrant.json
# Markdown SHA-256:   3bc0a4cf70a3ac6f0d3d8b55d0e1a60e6bbc8ab3a1f9f0409bd039883f6be217
# Code AST SHA-256:   a96cccd38a71f3c63170fa74bbde941cc35297292a9a142a5262454d2ee27811
# Verified Classes:   ResumptionUnverifiedError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ResumptionUnverifiedError(RuntimeError):
    """Raised when a reconnected MCP SSE stream cannot prove it is a
    continuation of the prior session at a later position."""


def verify_resumption(
    last_event_id: str,
    first_event_id: str,
    first_event_correlation: str | None,
    in_flight_correlations: set[str],
    ids_known_session_scoped: bool,
) -> None:
    """Gate the first post-reconnect event. Raises if the stream must be
    abandoned and the session restarted from scratch."""
    if not ids_known_session_scoped:
        raise ResumptionUnverifiedError(
            f"no evidence event IDs are session-scoped; refusing to resume "
            f"from Last-Event-ID={last_event_id!r}"
        )

    try:
        last = int(last_event_id)
        first = int(first_event_id)
    except ValueError as exc:
        raise ResumptionUnverifiedError(
            f"non-numeric event IDs {last_event_id!r} -> {first_event_id!r}; "
            f"cannot verify ordering"
        ) from exc

    if first <= last:
        raise ResumptionUnverifiedError(
            f"event ID reset or reused: Last-Event-ID={last}, "
            f"first post-reconnect ID={first}; server counter is "
            f"connection-local, not session-durable"
        )

    if first_event_correlation is not None and first_event_correlation not in in_flight_correlations:
        raise ResumptionUnverifiedError(
            f"first post-reconnect event correlates to "
            f"{first_event_correlation!r}, not in in-flight set "
            f"{sorted(in_flight_correlations)!r}; stream is not a "
            f"continuation of the prior session"
        )


def on_reconnect(last_event_id: str, first_event: dict, in_flight: set[str], scoped: bool) -> None:
    verify_resumption(
        last_event_id=last_event_id,
        first_event_id=first_event["id"],
        first_event_correlation=first_event.get("correlation"),
        in_flight_correlations=in_flight,
        ids_known_session_scoped=scoped,
    )
