# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-http-session-resumption-as-invalid-after-an-sse-to-post-upgrade.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-http-session-resumption-as-invalid-after-an-sse-to-post-upgrade.warrant.json
# Markdown SHA-256:   fad0e644fc673995054779d547a8334ccb9f3c7bafec1166dbe3445f839c0416
# Code AST SHA-256:   5e69f87fff2731babf010e9e2d252a3f5e432081aad3f514bb2c0515c75471ab
# Verified Classes:   ResumeTokenInvalidError, LegContext, ResumeToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ResumeTokenInvalidError(RuntimeError):
    """Raised when a Last-Event-ID is reused across an incompatible transport leg."""
    pass


@dataclass(frozen=True)
class LegContext:
    leg_id: str
    method: str                 # "GET" (SSE) or "POST"
    log_namespace: str          # server-declared event-log namespace
    committed_watermark: Optional[int]  # highest durably committed event id


@dataclass(frozen=True)
class ResumeToken:
    last_event_id: int
    issued_leg_id: str
    issued_namespace: str


def validate_resume_on_upgrade(
    token: ResumeToken,
    target_leg: LegContext,
    declares_unified_log: bool,
) -> None:
    """
    Enforce: a resume token is valid on a new leg only if the server
    declares a unified event log AND the target leg's committed watermark
    covers the token's last_event_id.
    """
    if target_leg.log_namespace != token.issued_namespace and not declares_unified_log:
        raise ResumeTokenInvalidError(
            f"resume token from namespace {token.issued_namespace!r} "
            f"cannot cross into {target_leg.log_namespace!r} without unified-log declaration"
        )

    if target_leg.committed_watermark is None:
        raise ResumeTokenInvalidError(
            f"leg {target_leg.leg_id!r} has no committed watermark; "
            "Last-Event-ID cannot be validated, treat token as leg-local"
        )

    if token.last_event_id > target_leg.committed_watermark:
        raise ResumeTokenInvalidError(
            f"resume token id {token.last_event_id} exceeds committed watermark "
            f"{target_leg.committed_watermark} on leg {target_leg.leg_id!r}; "
            "refusing to replay POST"
        )


def resume_or_restart(
    token: ResumeToken,
    target_leg: LegContext,
    declares_unified_log: bool,
) -> str:
    try:
        validate_resume_on_upgrade(token, target_leg, declares_unified_log)
    except ResumeTokenInvalidError:
        # Invalid resume: do NOT retry the POST with a stale token.
        # Invalidate session and resume from durable checkpoint.
        return "restart_from_checkpoint"
    return "resume_on_leg"
