# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-resumed-mcp-session-s-sse-last-event-id-as-non-authoritative-after-a-transport-downgrade.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-resumed-mcp-session-s-sse-last-event-id-as-non-authoritative-after-a-transport-downgrade.warrant.json
# Markdown SHA-256:   87d7529b8acf6df9bd5d5f144eb392781f0bbbd634bb1404ed76361e4ab3f6d3
# Code AST SHA-256:   3c92cb0311dad03d800f8e1acd91e95d21cfea6e764cb14b2b9545bb658e2958
# Verified Classes:   ResumeAmbiguityError, ReconnectContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ResumeAmbiguityError(RuntimeError):
    """Raised when a session resume cannot be proven authoritative."""


@dataclass
class ReconnectContext:
    cursor: Optional[str]
    cursor_epoch: Optional[str]
    server_epoch: Optional[str]
    replay_complete_asserted: bool
    transport: str  # "stream" | "sse"


def decide_resume(ctx: ReconnectContext) -> str:
    """
    Returns "replay" or "resync". Raises ResumeAmbiguityError when the
    caller has asked us to replay but the cursor is not provably authoritative
    within the current transport epoch.
    """
    if ctx.cursor is None:
        return "resync"

    if ctx.server_epoch is None:
        # No epoch marker: cursor is advisory. We cannot prove continuity.
        raise ResumeAmbiguityError(
            f"server did not expose an epoch marker; cursor {ctx.cursor!r} "
            f"from transport {ctx.transport!r} cannot be trusted for replay"
        )

    if ctx.cursor_epoch != ctx.server_epoch:
        # Cursor minted in a different epoch than the one we are reconnecting into.
        raise ResumeAmbiguityError(
            f"cursor epoch {ctx.cursor_epoch!r} != server epoch "
            f"{ctx.server_epoch!r}; transport downgrade likely reset the "
            f"event counter, replay would silently skip events"
        )

    if not ctx.replay_complete_asserted:
        # Empty replay on a fresh buffer is indistinguishable from lost replay.
        raise ResumeAmbiguityError(
            f"server did not assert replay_complete for cursor {ctx.cursor!r}; "
            f"empty stream cannot be distinguished from dropped events"
        )

    return "replay"


def attempt_resume(ctx: ReconnectContext) -> str:
    try:
        action = decide_resume(ctx)
    except ResumeAmbiguityError:
        # Hard resync: discard cursor, refetch authoritative state.
        return "resync"
    return action
