# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-streamable-session-resumption-from-silently-forking-agent-state-across-sse-to-http-upgrades.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-streamable-session-resumption-from-silently-forking-agent-state-across-sse-to-http-upgrades.warrant.json
# Markdown SHA-256:   fa714dd1963c194f8e84b726ee5b84b6e8362d963e981603e88a83309a809ce1
# Code AST SHA-256:   c14eda5c42dc6a2168d84988648d0f2ff8101cfc705ef670da5b390e65bf6710
# Verified Classes:   ResumptionForkError, OutcomeClass, SessionCursor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ResumptionForkError(RuntimeError):
    """Raised when a streamable-session resumption would fork agent state."""
    pass


class OutcomeClass(Enum):
    REPLAYED = "replayed"          # tool result is authoritative
    GAP_RESYNCED = "gap_resynced"  # tool may have run 0..N times; must re-verify
    SESSION_LOST = "session_lost"  # effect unknown; do not proceed on dependent beliefs


@dataclass
class SessionCursor:
    session_id: str
    last_event_id: int
    last_request_seq: int
    idempotency_tokens: dict[int, str] = field(default_factory=dict)


def idempotency_token(session_id: str, request_seq: int, payload: bytes) -> str:
    h = hashlib.sha256()
    h.update(session_id.encode())
    h.update(b"|")
    h.update(str(request_seq).encode())
    h.update(b"|")
    h.update(payload)
    return h.hexdigest()


def classify_resumption(
    cursor: SessionCursor,
    server_status: str,
    replayed_through: Optional[int],
    gap: Optional[tuple[int, int]],
) -> OutcomeClass:
    if server_status == "404" or server_status == "410":
        return OutcomeClass.SESSION_LOST
    if server_status == "200" and replayed_through is not None:
        if replayed_through >= cursor.last_request_seq:
            return OutcomeClass.REPLAYED
        # server replayed past our cursor but not through our last request
        return OutcomeClass.GAP_RESYNCED
    if server_status == "200" and gap is not None:
        return OutcomeClass.GAP_RESYNCED
    # empty 200 with no status probe result — ambiguous, must not be treated as complete
    raise ResumptionForkError(
        f"session {cursor.session_id}: empty replay at Last-Event-ID="
        f"{cursor.last_event_id} with no gap signal; treating as complete would "
        f"re-execute request_seq={cursor.last_request_seq}"
    )


def resume_and_maybe_reexecute(
    cursor: SessionCursor,
    server_status: str,
    replayed_through: Optional[int],
    gap: Optional[tuple[int, int]],
    payload: bytes,
) -> OutcomeClass:
    outcome = classify_resumption(cursor, server_status, replayed_through, gap)
    if outcome is OutcomeClass.REPLAYED:
        return outcome
    if outcome is OutcomeClass.GAP_RESYNCED:
        lo, hi = gap if gap is not None else (replayed_through or 0, cursor.last_request_seq)
        if cursor.last_request_seq < lo or cursor.last_request_seq > hi:
            raise ResumptionForkError(
                f"request_seq={cursor.last_request_seq} outside gap [{lo},{hi}]; "
                f"re-execution would fork state"
            )
        expected = cursor.idempotency_tokens.get(cursor.last_request_seq)
        actual = idempotency_token(cursor.session_id, cursor.last_request_seq, payload)
        if expected is None or expected != actual:
            raise ResumptionForkError(
                f"idempotency token mismatch for request_seq={cursor.last_request_seq}; "
                f"refusing to re-execute mutating call"
            )
        return outcome
    # SESSION_LOST
    raise ResumptionForkError(
        f"session {cursor.session_id} lost; tool effect unknown, agent must "
        f"re-verify via independent read before proceeding"
    )
