# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-sse-to-post-upgrade-negotiation-from-silently-orphaning-a-resumable-mcp-session.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-sse-to-post-upgrade-negotiation-from-silently-orphaning-a-resumable-mcp-session.warrant.json
# Markdown SHA-256:   08d31ef7a55ed372afd5ea19ecfeffaee9ed34fd1489b836e192a0a9eedf3a39
# Code AST SHA-256:   972decc1dbfb6ee37501bae83f04c4575b74a645510e797752d828fd60311e4f
# Verified Classes:   OrphanedStreamError, LegConflationError, SessionState
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class OrphanedStreamError(RuntimeError):
    """Raised when a resume would write replayed events into a stream with no reader."""
    pass


class LegConflationError(RuntimeError):
    """Raised when a resume POST returns 200-with-body, conflating the POST and SSE legs."""
    pass


@dataclass
class SessionState:
    session_id: str
    last_emitted_event_id: int = 0
    open_streams: dict = field(default_factory=dict)   # stream_id -> reader_attached
    stream_seq: int = 0


def handle_resume_post(
    session: SessionState,
    last_event_id: int,
    echoed_stream_id: Optional[str],
    now: float,
) -> dict:
    """
    Server-side resume handler. Enforces the leg-affinity invariant:
    a resume POST may only re-bind an OPEN SSE stream; otherwise it must 409.
    """
    # Invariant check 1: cursor must not be ahead of the log (client bug or replay attack).
    if last_event_id > session.last_emitted_event_id:
        raise OrphanedStreamError(
            f"resume cursor {last_event_id} ahead of log head "
            f"{session.last_emitted_event_id} for session {session.session_id}"
        )

    # Invariant check 2: leg affinity. The client must echo a stream ID that is
    # still open AND still has a reader attached. If not, refuse and force GET.
    if echoed_stream_id is None:
        return {
            "status": 409,
            "headers": {"Mcp-Resume-Via": "GET"},
            "reason": "no_stream_id_echoed",
        }

    reader_attached = session.open_streams.get(echoed_stream_id)
    if reader_attached is None:
        # Stream was torn down. A 200 here would open an orphaned stream.
        return {
            "status": 409,
            "headers": {"Mcp-Resume-Via": "GET"},
            "reason": "stream_not_open",
        }
    if not reader_attached:
        # Stream is open but its reader has disconnected. Same hazard.
        return {
            "status": 409,
            "headers": {"Mcp-Resume-Via": "GET"},
            "reason": "stream_reader_detached",
        }

    # Safe to re-bind: replay the gap into the SAME stream, return bare 202.
    replay_count = session.last_emitted_event_id - last_event_id
    return {
        "status": 202,
        "headers": {"Mcp-Stream-Id": echoed_stream_id},
        "replayed_events": replay_count,
        "stream_id": echoed_stream_id,
    }


def client_resume(
    server_response: dict,
    sent_last_event_id: bool,
) -> str:
    """
    Client-side guard: never trust a 200 on a resume POST.
    Returns the leg the client must use next.
    """
    status = server_response.get("status")
    if sent_last_event_id and status == 200 and server_response.get("body"):
        # Server conflated legs: replayed events into a POST body. Do not read it.
        raise LegConflationError(
            "resume POST returned 200-with-body; replayed events are unreachable "
            "by the SSE reader. Discard body and re-issue as GET."
        )
    if status == 409:
        return "GET"
    if status == 202:
        return "SSE"
    raise OrphanedStreamError(f"unexpected resume status {status}")


def simulate_two_interruptions() -> None:
    s = SessionState(session_id="s-8812")
    s.last_emitted_event_id = 53
    s.stream_seq = 1
    s.open_streams["stream-1"] = True

    # First interruption: client resumes via POST echoing stream-1 (still open).
    r1 = handle_resume_post(s, last_event_id=47, echoed_stream_id="stream-1", now=time.time())
    assert r1["status"] == 202, r1

    # Second interruption: server tore down stream-1 during the idle gap.
    s.open_streams["stream-1"] = False
    r2 = handle_resume_post(s, last_event_id=53, echoed_stream_id="stream-1", now=time.time())

    # The guardrail refuses the POST resume rather than opening an orphan.
    if r2["status"] != 409:
        raise OrphanedStreamError(
            f"POST resume on torn-down stream {r2.get('stream_id')} would orphan "
            f"events {53}..{s.last_emitted_event_id}"
        )

    leg = client_resume(r2, sent_last_event_id=True)
    assert leg == "GET", leg


if __name__ == "__main__":
    simulate_two_interruptions()
