# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-mcp-last-event-id-resumption-as-a-semantic-fork-rather-than-a-replay-and-refuse-to-resume.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-mcp-last-event-id-resumption-as-a-semantic-fork-rather-than-a-replay-and-refuse-to-resume.warrant.json
# Markdown SHA-256:   5e90be97adc8a70ab875ca6e4107ca0f1fb737eae20fd1ed6cfb2a3efa1fcc8e
# Code AST SHA-256:   fa275895d66a403761b12d62b5bb1d891eab1cc931ed01d057fcc86e0d534a07
# Verified Classes:   ResumptionForkError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ResumptionForkError(RuntimeError):
    """Raised when an SSE resumption would bind to a different session epoch."""


def resume_stream(held_session_id: str, held_last_event_id: int, handshake: dict) -> dict:
    server_session = handshake.get("session_id")
    server_last_event = handshake.get("last_event_id")

    if server_session != held_session_id:
        # Session was reaped or replaced; the event-ID space is a new epoch.
        raise ResumptionForkError(
            f"epoch change: held session {held_session_id!r} != server {server_session!r}; "
            f"in-flight outcome indeterminate, must reconcile not retry"
        )

    if server_last_event is None:
        raise ResumptionForkError(
            f"server accepted resumption for session {server_session!r} but returned no "
            f"event-ID cursor; cannot verify replay determinism"
        )

    if server_last_event <= held_last_event_id:
        # Same session, but cursor moved backward: namespace reset without epoch change.
        raise ResumptionForkError(
            f"cursor regression within session {server_session!r}: "
            f"server {server_last_event} <= held {held_last_event_id}; treat as fork"
        )

    return handshake
