# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-sse-to-streamable-http-migration-as-a-session-identity-fork-rather-than-a-transport-swap.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-sse-to-streamable-http-migration-as-a-session-identity-fork-rather-than-a-transport-swap.warrant.json
# Markdown SHA-256:   5997c5d50e2c96ff3b172879ce2f649bcb934bca8cb32f509b93d1d8f1cc414c
# Code AST SHA-256:   8a6f9de554da153479ef957b12e381b25e94005ab78d6b833dd6eaf97550b3f0
# Verified Classes:   SessionForkError, StreamCursor, SessionStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SessionForkError(RuntimeError):
    """Raised when a stream reconnect would silently fork session identity."""


@dataclass
class StreamCursor:
    transport_generation: str      # e.g. "legacy-sse" or "streamable-http-v1"
    session_id: str
    last_event_id: Optional[str]   # None if no events yet, or after migration


@dataclass
class SessionStore:
    # Maps (generation, session_id) -> retained event-id set for that session.
    events: dict[tuple[str, str], set[str]] = field(default_factory=dict)
    # Maps (generation, session_id) -> generation that superseded it, if any.
    superseded: dict[tuple[str, str], str] = field(default_factory=dict)

    def register(self, generation: str, session_id: str, event_ids: set[str]) -> None:
        self.events[(generation, session_id)] = set(event_ids)

    def resolve_resume(self, cursor: StreamCursor) -> str:
        """
        Validate a resumption request. Returns the resolved session_id on success.
        Raises SessionForkError on any condition that would fork identity.
        """
        key = (cursor.transport_generation, cursor.session_id)

        if key not in self.events:
            # Unknown session on this generation: MUST be an explicit 404-equivalent,
            # never a silent fresh-session mint that the client mistakes for a resume.
            raise SessionForkError(
                f"unknown session {cursor.session_id!r} on transport "
                f"{cursor.transport_generation!r}; client must re-initialize"
            )

        if cursor.last_event_id is None:
            # Fresh stream on a known session: legal.
            return cursor.session_id

        if cursor.last_event_id not in self.events[key]:
            # Cursor points into a namespace this session never issued.
            # This is the exact legacy->streamable migration fork: the client
            # carries an event id from the old transport into the new session store.
            raise SessionForkError(
                f"Last-Event-ID {cursor.last_event_id!r} not in retained log for "
                f"session {cursor.session_id!r} (generation "
                f"{cursor.transport_generation!r}); refusing silent replay-from-head"
            )

        return cursor.session_id

    def migrate(self, old_gen: str, old_sid: str, new_gen: str, new_sid: str,
                carried_event_ids: set[str]) -> None:
        """
        Explicit migration. Carried event ids are recorded as *precursor* markers
        so a client that mistakenly replays one gets a typed fork error rather
        than a silent replay, while genuinely new events get fresh ids.
        """
        self.superseded[(old_gen, old_sid)] = new_gen
        # New session starts with an empty retained log. Any legacy cursor is
        # by construction absent from it.
        self.register(new_gen, new_sid, carried_event_ids)


def resume_stream(store: SessionStore, cursor: StreamCursor) -> str:
    """Entry point the transport layer calls on every GET /mcp (or GET /sse)."""
    try:
        return store.resolve_resume(cursor)
    except SessionForkError as exc:
        # Surface as a typed protocol error; client MUST orphan outstanding
        # JSON-RPC requests and re-initialize rather than trust the open stream.
        raise SessionForkError(f"resumption refused: {exc}") from exc


def idempotency_key(session_id: str, jsonrpc_id: str) -> str:
    """Stable key so a post-fork re-issue dedupes against the orphaned original."""
    return hashlib.sha256(f"{session_id}\x00{jsonrpc_id}".encode()).hexdigest()


# --- Reproduction of the observed failure ---
if __name__ == "__main__":
    store = SessionStore()
    store.register("legacy-sse", "sess-A", {"39", "40", "41"})
    # Migration: new endpoint, new session id, no retained legacy events.
    store.migrate("legacy-sse", "sess-A", "streamable-http-v1", "sess-B", set())

    # Client mistakenly replays legacy cursor 41 against the new endpoint.
    bad = StreamCursor(
        transport_generation="streamable-http-v1",
        session_id="sess-B",
        last_event_id="41",
    )
    try:
        resume_stream(store, bad)
    except SessionForkError as e:
        print(f"[caught] {e}")
        print("action: orphan outstanding tools/call, re-initialize, re-issue with "
              f"idempotency key {idempotency_key('sess-A', 'call-7')[:16]}…")
