# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-after-sse-to-streamable-http-migration-and-the-event-id-namespace-silently-resets.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-after-sse-to-streamable-http-migration-and-the-event-id-namespace-silently-resets.warrant.json
# Markdown SHA-256:   64aa576ab5685482a3b30164d48b24be449a1695f71d94e3c1a0ae81f3b437d2
# Code AST SHA-256:   21537b677b74b1d1ca6efd35c47f0082a3fbe1436f43b76bd81bc0c162bff6d0
# Verified Classes:   CursorNamespaceError, ResumeCursor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class CursorNamespaceError(RuntimeError):
    """Raised when a persisted Last-Event-ID cursor cannot be proven valid
    within the stream-scope it is being resumed against."""


@dataclass(frozen=True)
class ResumeCursor:
    session_id: str
    transport_generation: str
    stream_scope: str
    event_id: int


def validate_resume(
    cursor: ResumeCursor,
    server_generation: str,
    first_event_scope: str,
    first_event_id: int,
) -> bool:
    # Transport migration invalidates the cursor's namespace entirely.
    if cursor.transport_generation != server_generation:
        raise CursorNamespaceError(
            f"cursor minted under generation {cursor.transport_generation!r} "
            f"cannot resume against {server_generation!r}; re-issue request"
        )

    # The stream we are attaching to must be the same scope the cursor came from.
    if cursor.stream_scope != first_event_scope:
        raise CursorNamespaceError(
            f"cursor scope {cursor.stream_scope!r} != stream scope "
            f"{first_event_scope!r}; possible cross-stream collision"
        )

    # Within a validated scope, resumption requires strict forward progress.
    if first_event_id <= cursor.event_id:
        raise CursorNamespaceError(
            f"first event id {first_event_id} not > cursor {cursor.event_id} "
            f"within scope {first_event_scope!r}; namespace reset detected"
        )

    return True


def resume_or_restart(cursor, server_generation, first_event_scope, first_event_id):
    try:
        validate_resume(cursor, server_generation, first_event_scope, first_event_id)
    except CursorNamespaceError:
        # Fall back to a clean re-issue with an idempotency key rather than
        # continuing a stream whose numbering we cannot trust.
        return {"action": "restart", "idempotency_key": cursor.session_id}
    return {"action": "resume", "from": cursor.event_id}
