# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-mcp-resumable-stream-replay-as-authoritative-over-its-own-cached-tool-result-state.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-mcp-resumable-stream-replay-as-authoritative-over-its-own-cached-tool-result-state.warrant.json
# Markdown SHA-256:   e9dcd7f239fc3c681f7992ad48435977ad177ab99f3b0d25e71d3a0389a3baf8
# Code AST SHA-256:   d3b117b9acde63594d626fbdf7fd77d27e943126bfcd0cabe73cafc343e5d252
# Verified Classes:   ResumableSessionViolation, CachedCall, ResumableSession
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ResumableSessionViolation(RuntimeError):
    """Raised when an MCP resumable SSE replay cannot be safely reconciled
    with the client's cached tool-call state."""
    pass


@dataclass
class CachedCall:
    request_id: int
    terminal: bool = False
    payload: Optional[dict] = None
    scratch_artifacts: list = field(default_factory=list)


class ResumableSession:
    """Tracks the durable high-water mark of SSE event IDs and reconciles
    replayed events against cached tool-call results.

    Invariant: any event with id > high_water_mark is authoritative and
    evicts cached terminal state for the referenced request_id.
    """

    def __init__(self) -> None:
        self.high_water_mark: int = -1
        self.calls: Dict[int, CachedCall] = {}

    def observe(self, event_id: int, request_id: int, is_terminal: bool,
                payload: Optional[dict] = None) -> None:
        # Non-monotonic replay: server reset its event ID space or we are
        # replaying from a stale checkpoint. Session identity is lost.
        if event_id <= self.high_water_mark:
            # Duplicate within the same ID space is a benign drop ONLY if
            # the ID equals the mark; anything strictly below means the
            # server rewound, which invalidates the whole cache.
            if event_id < self.high_water_mark:
                raise ResumableSessionViolation(
                    f"non-monotonic replay: event {event_id} < "
                    f"high-water mark {self.high_water_mark}; session reset"
                )
            return  # exact duplicate, drop

        existing = self.calls.get(request_id)
        if existing is None:
            # Continuation of a request we never saw begin. Cannot safely
            # bind it to prior scratch state.
            if not is_terminal:
                self.calls[request_id] = CachedCall(request_id=request_id)
            else:
                raise ResumableSessionViolation(
                    f"orphaned terminal replay for request {request_id} "
                    f"at event {event_id}: no pending call to continue"
                )
        else:
            # THE BOUNDARY: replayed event past the mark is authoritative.
            # Evict any cached terminal frame and scratch derived from an
            # aborted attempt before applying the replayed payload.
            if existing.terminal:
                existing.terminal = False
                existing.payload = None
                existing.scratch_artifacts.clear()

        if is_terminal:
            self.calls[request_id].terminal = True
            self.calls[request_id].payload = payload

        self.high_water_mark = event_id

    def last_event_id_header(self) -> str:
        if self.high_water_mark < 0:
            raise ResumableSessionViolation("no events observed; cannot resume")
        return str(self.high_water_mark)


def resume_stream(session: ResumableSession, replayed_events: list) -> None:
    """Apply a server replay. Raises if the replay cannot be trusted as a
    monotonic continuation of the durable high-water mark."""
    if not replayed_events:
        return
    first_id = replayed_events[0][0]
    if first_id <= session.high_water_mark and first_id != session.high_water_mark + 1:
        # Server did not resume from our mark; ordering guarantee is void.
        raise ResumableSessionViolation(
            f"replay starts at {first_id}, expected > {session.high_water_mark}"
        )
    for event_id, request_id, is_terminal, payload in replayed_events:
        session.observe(event_id, request_id, is_terminal, payload)
