# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-an-mcp-resumption-token-as-a-replay-cursor-rather-than-a-session-identity.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-an-mcp-resumption-token-as-a-replay-cursor-rather-than-a-session-identity.warrant.json
# Markdown SHA-256:   3e2f147ca3d38dab49039835f7ce5c54bbe903e28e286fcacfc570b5c497f6fa
# Code AST SHA-256:   30c3e8d9c2ea26563f8a1d12d482c00bca545eb16a7bb7b60e8ab1f8e41ab488
# Verified Classes:   ResumptionCursorError, StreamCursor, ReconnectAck, CheckpointStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ResumptionCursorError(RuntimeError):
    """Raised when a resumption token cannot be trusted as a continuity cursor."""
    pass


@dataclass
class StreamCursor:
    session_id: str
    generation: int
    last_event_id: str


@dataclass
class ReconnectAck:
    session_id: str
    generation: int
    resumed_from_event_id: str
    sequence_reset: bool


@dataclass
class CheckpointStore:
    # Maps idempotency key -> durable result digest. Source of truth.
    committed: dict = field(default_factory=dict)

    def has(self, key: str) -> bool:
        return key in self.committed

    def commit(self, key: str, result: str) -> None:
        self.committed[key] = hashlib.sha256(result.encode()).hexdigest()


def reconcile_resumption(
    cursor: StreamCursor,
    ack: ReconnectAck,
    store: CheckpointStore,
    inflight_tool_call_id: str,
) -> str:
    """
    Decide whether the resumed stream is continuous with `cursor`, and whether
    any in-flight tool call must be re-issued because its result may have
    fallen into a replay gap.
    """
    # Generation change means the event-ID namespace was reset: the old cursor
    # is meaningless and must not be used for dedup or gap reasoning.
    if ack.generation != cursor.generation:
        raise ResumptionCursorError(
            f"stream generation changed {cursor.generation}->{ack.generation}; "
            f"cursor {cursor.last_event_id!r} is orphaned, must re-establish state"
        )

    # Server acknowledged a different resume point than we requested: there is
    # a hole between our cursor and the server's head. We cannot assume the
    # in-flight tool result was delivered.
    if ack.resumed_from_event_id != cursor.last_event_id:
        if store.has(inflight_tool_call_id):
            # Result is durably checkpointed; safe to proceed, hole is benign.
            return "resume_with_checkpoint"
        raise ResumptionCursorError(
            f"replay gap: requested {cursor.last_event_id!r}, "
            f"server resumed at {ack.resumed_from_event_id!r}; "
            f"in-flight tool call {inflight_tool_call_id!r} not checkpointed"
        )

    # Cursor matched and generation stable: replay is continuous, but events
    # are still at-least-once. Caller must dedup on idempotency key.
    return "resume_continuous_but_dedup"


def handle_reconnect(cursor, ack, store, inflight_tool_call_id):
    mode = reconcile_resumption(cursor, ack, store, inflight_tool_call_id)
    if mode == "resume_with_checkpoint":
        return "proceed"
    return "proceed_dedup"
