# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-mcp-notifications-cancelled-during-session-resumption-because-the-resumable-stream-s-replay-cursor-and-the-c.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-mcp-notifications-cancelled-during-session-resumption-because-the-resumable-stream-s-replay-cursor-and-the-c.warrant.json
# Markdown SHA-256:   80c21fee24d3acf0b0322b05988f80dd05acb1e231f66351890ce2e3dc19f9c7
# Code AST SHA-256:   676ef1799d873ab9e5ca217ece73c2b339fb31d3c9fa5942cc2fd0a787295412
# Verified Classes:   CancellationOrderingViolation, Event, Session
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Dict, List, Optional


class CancellationOrderingViolation(RuntimeError):
    """Raised when a cancellation cannot be safely applied against a replay window."""


@dataclass
class Event:
    seq: int
    kind: str  # "progress" | "result" | "cancelled"
    request_id: str


@dataclass
class Session:
    session_id: str
    event_log: List[Event] = field(default_factory=list)
    # request_id -> last seq the client has acknowledged receiving
    client_ack: Dict[str, int] = field(default_factory=dict)
    # request_id -> seq at which the deferred cancel should take effect
    pending_cancellations: Dict[str, int] = field(default_factory=dict)

    def head_seq(self, request_id: str) -> int:
        seqs = [e.seq for e in self.event_log if e.request_id == request_id]
        return max(seqs) if seqs else 0


def handle_cancellation(
    session: Session,
    request_id: str,
    cancel_stream_position: Optional[int],
    cancel_arrival_seq: int,
) -> str:
    """
    Decide whether to apply, defer, or reject a notifications/cancelled.

    cancel_stream_position: value from the cancel, if the client supplied one
                            (MCP does not currently define this field; None is
                            the common case and the one that triggers deferral).
    cancel_arrival_seq:     the server's event-log position at the instant the
                            cancel was received. Used as the causal upper bound
                            for the deferral window.
    """
    ack = session.client_ack.get(request_id, 0)
    head = session.head_seq(request_id)

    # Stale epoch: cancel references a request whose log predates the session's
    # current generation. Must not be honored — cross-session requestId collision.
    if head == 0 and ack == 0:
        raise CancellationOrderingViolation(
            f"cancel for unknown/stale request {request_id!r} in session "
            f"{session.session_id!r}; refusing to apply"
        )

    # Case 1: client supplied an explicit stream position at or after head.
    # Causality is established; apply immediately.
    if cancel_stream_position is not None and cancel_stream_position >= head:
        return "applied_immediately"

    # Case 2: replay window is empty — client is fully caught up.
    # Cancel is causally safe.
    if ack >= head:
        return "applied_immediately"

    # Case 3: non-empty replay window, no stream position on the cancel.
    # Defer: the cancel takes effect at cancel_arrival_seq, but only after the
    # client has acknowledged every event up to that seq.
    deferral_seq = min(cancel_arrival_seq, head)
    if deferral_seq <= ack:
        # The cancel "arrived" before anything the client hasn't seen; it is
        # effectively a no-op against the replay window, but must still be
        # surfaced as a terminal event at the trailing edge.
        deferral_seq = ack + 1

    session.pending_cancellations[request_id] = deferral_seq
    return f"deferred_until_ack_{deferral_seq}"


def drain_pending_cancellations(session: Session, request_id: str) -> List[Event]:
    """Emit a synthetic cancelled terminal event only once the client has
    acknowledged the replay prefix up to the deferral point."""
    target = session.pending_cancellations.get(request_id)
    if target is None:
        return []
    if session.client_ack.get(request_id, 0) < target - 1:
        # Client has not yet acknowledged the prefix the cancel must trail.
        return []
    del session.pending_cancellations[request_id]
    terminal = Event(seq=session.head_seq(request_id) + 1,
                     kind="cancelled", request_id=request_id)
    session.event_log.append(terminal)
    return [terminal]
