# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-sse-session-was-silently-forked-during-a-streamablehttp-upgrade.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-sse-session-was-silently-forked-during-a-streamablehttp-upgrade.warrant.json
# Markdown SHA-256:   5b0ef2ed60bc6606227d8bec8b13d9f1d713496f30dc8e84d6291a22ec269bd9
# Code AST SHA-256:   f74f8434207a672765cdd58524f39947dcac83d45f4193655fcb773bff6343c2
# Verified Classes:   SessionForkError, SessionTuple
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SessionForkError(RuntimeError):
    """Raised when an MCP transport upgrade silently forks session identity
    while requests are in flight, making continuation vs. fork undecidable."""


@dataclass(frozen=True)
class SessionTuple:
    session_id: str
    last_event_id: int
    pending_requests: int


def classify_upgrade(
    pre: SessionTuple,
    post_session_id: str,
    replay_from: Optional[int],
    policy: str,  # "continuation" | "fork"
) -> str:
    """Return 'continue' or 'fork' or raise SessionForkError.

    The gate must be called BEFORE the client reads the new stream body.
    """
    if pre.pending_requests == 0:
        # No in-flight work: either policy is safe, transition is a fork.
        return "fork"

    if post_session_id == pre.session_id:
        # Same identity: continuation is safe regardless of replay marker.
        return "continue"

    # Session id changed with pending requests in flight.
    if policy == "continuation":
        if replay_from is None:
            raise SessionForkError(
                f"upgrade changed session {pre.session_id!r} -> {post_session_id!r} "
                f"with {pre.pending_requests} pending request(s) and no replay-from "
                f"marker; cannot prove continuation"
            )
        if replay_from > pre.last_event_id + 1:
            raise SessionForkError(
                f"replay-from {replay_from} skips events "
                f"{pre.last_event_id + 1}..{replay_from - 1}; pending result may be lost"
            )
        return "continue"

    if policy == "fork":
        # Fork policy is only safe if the caller cancels pending requests
        # and does not deduplicate against the old cursor.
        return "fork"

    raise SessionForkError(f"unknown upgrade policy {policy!r}")


def apply_upgrade(pre: SessionTuple, post_session_id: str,
                  replay_from: Optional[int], policy: str) -> str:
    decision = classify_upgrade(pre, post_session_id, replay_from, policy)
    if decision == "fork" and pre.pending_requests > 0:
        # Caller MUST cancel pending requests before consuming new stream.
        # We raise here to force the caller to make that explicit.
        raise SessionForkError(
            f"fork decision with {pre.pending_requests} pending request(s); "
            f"caller must cancel and re-issue with idempotency keys before "
            f"consuming session {post_session_id!r}"
        )
    return decision
