# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-sse-resumption-as-a-state-reconstruction-problem-rather-than-a-byte-replay-problem.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-sse-resumption-as-a-state-reconstruction-problem-rather-than-a-byte-replay-problem.warrant.json
# Markdown SHA-256:   e5e26d9443a46202fa0fde92810c09bc0e6bdb38a8af2e54123c225c4611bb05
# Code AST SHA-256:   01f926184959fc01da7c377bbb0ec22fbc80692f9f7496402cd26ef8b474f0a2
# Verified Classes:   SessionResumeForkError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SessionResumeForkError(RuntimeError):
    """Raised when a resumed SSE stream's replayed events contradict the client's outbound ledger."""
    pass


def resume_session(client, session_id: str, last_event_id: str):
    stream = client.open_sse(session_id, last_event_id=last_event_id)
    last_progress = client.ledger.last_observed_progress(session_id)

    for event in stream:
        # Invariant 1: progress counters must strictly continue.
        if event.type == "notifications/progress":
            if event.progress_token <= last_progress:
                raise SessionResumeForkError(
                    f"progress regression on resume: saw {event.progress_token} "
                    f"after {last_progress} (session {session_id})"
                )
            last_progress = event.progress_token

        # Invariant 2: server-initiated requests must not be replayed
        # against a client that already recorded an outbound answer.
        if event.type in ("sampling/createMessage", "elicitation/create"):
            if client.ledger.has_outbound(session_id, event.request_id):
                raise SessionResumeForkError(
                    f"server re-emitted request {event.request_id} that client "
                    f"already answered; replay/reconstruction boundary crossed"
                )

    return stream
