# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-the-replay-window-when-resuming-an-mcp-streamable-http-session-whose-sse-cursor-was-re-anchored-by-the-server.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-the-replay-window-when-resuming-an-mcp-streamable-http-session-whose-sse-cursor-was-re-anchored-by-the-server.warrant.json
# Markdown SHA-256:   dcdec5c8097710bbfc8132d17132d2578d6ce090fe6b7dbe2dfb74828075cd75
# Code AST SHA-256:   0953fd7f4f0acbc2d2f40b66e869a6e78f09d6b84e76fed6cd138e4b51f8314f
# Verified Classes:   ReplayWindowViolation, ResumeState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ReplayWindowViolation(RuntimeError):
    """Raised when a resumed MCP stream cannot be trusted as a contiguous continuation."""
    pass


@dataclass
class ResumeState:
    epoch: str
    last_seen_id: int
    dispatch_log: dict = field(default_factory=dict)  # idempotency_key -> logical call


def resume_stream(state: ResumeState, first_frame: dict) -> str:
    """
    Decide whether the first frame after resume is a trustworthy continuation.
    Returns 'trusted' | 'gap' | 'reconcile'.
    Raises ReplayWindowViolation when the frame is actionable but unverifiable.
    """
    frame_epoch = first_frame.get("epoch")
    frame_id = first_frame.get("id")
    frame_kind = first_frame.get("kind")

    # No epoch metadata: server cannot prove continuity.
    if frame_epoch is None:
        raise ReplayWindowViolation(
            f"resume without epoch tag; cannot verify contiguity (last_seen={state.last_seen_id})"
        )

    # Epoch rollover: different timeline, full reconciliation required.
    if frame_epoch != state.epoch:
        return "reconcile"

    # Same epoch but non-contiguous: a gap of unknown size exists.
    if frame_id != state.last_seen_id + 1:
        # A tool result arriving across a gap is the dangerous case.
        if frame_kind == "tools/call_result":
            key = first_frame.get("idempotency_key")
            if key not in state.dispatch_log:
                raise ReplayWindowViolation(
                    f"orphan tool result id={frame_id} for undispatched call key={key}; "
                    f"gap spans {state.last_seen_id}..{frame_id}"
                )
        return "gap"

    return "trusted"


def apply_frame(state: ResumeState, frame: dict) -> None:
    verdict = resume_stream(state, frame)
    if verdict == "reconcile":
        raise ReplayWindowViolation(
            f"epoch mismatch: client={state.epoch} server={frame.get('epoch')}; "
            "re-fetch authoritative state before consuming frames"
        )
    if verdict == "gap":
        # Drain; only re-establish on a fresh request frame or explicit sentinel.
        if frame.get("kind") == "tools/call_request":
            state.dispatch_log[frame["idempotency_key"]] = frame
        state.last_seen_id = frame["id"]
        return
    state.last_seen_id = frame["id"]
