# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-a-resumable-mcp-stream-has-silently-lost-its-resume-point-under-http-native-backpressure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-a-resumable-mcp-stream-has-silently-lost-its-resume-point-under-http-native-backpressure.warrant.json
# Markdown SHA-256:   7e67d31eab62e9599ec83d41bee12bdfabec8c405798241383ea325fcddd4c14
# Code AST SHA-256:   59c7bd6f76d41a71a42392c797c1d36a77af9dbc7081b6fbd92f5364202af069
# Verified Classes:   ResumeDivergenceError, CommittedEvent, ReplayedEvent
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ResumeDivergenceError(RuntimeError):
    """Raised when a replayed MCP stream event is cursor-continuous but
    content-divergent from the producer's durable commit log for the same
    logical operation. Transport resume succeeded; semantic resume failed."""
    pass


@dataclass(frozen=True)
class CommittedEvent:
    operation_id: str
    cursor: int
    payload_hash: str


@dataclass(frozen=True)
class ReplayedEvent:
    operation_id: str
    cursor: int
    payload: bytes


def verify_resume(
    last_event_id: int,
    replayed: list[ReplayedEvent],
    commit_log: dict[str, CommittedEvent],
) -> None:
    """Validate that a resumed stream is semantically continuous with the
    producer's commit log, not merely monotonically cursor-continuous.

    Invariant: every replayed event must match a committed event by
    operation_id AND payload_hash. Cursor monotonicity alone is insufficient
    because backpressure can drop un-cursored events and force re-execution.
    """
    expected_next = last_event_id + 1
    for ev in replayed:
        if ev.cursor != expected_next:
            raise ResumeDivergenceError(
                f"cursor gap: expected {expected_next}, got {ev.cursor} "
                f"for operation {ev.operation_id}"
            )
        committed = commit_log.get(ev.operation_id)
        if committed is None:
            raise ResumeDivergenceError(
                f"operation {ev.operation_id} at cursor {ev.cursor} has no "
                f"durable commit entry; event was produced but never "
                f"cursor-assigned before the backpressure gate"
            )
        actual_hash = hashlib.sha256(ev.payload).hexdigest()
        if actual_hash != committed.payload_hash:
            raise ResumeDivergenceError(
                f"operation {ev.operation_id} at cursor {ev.cursor} "
                f"replayed with divergent payload: committed "
                f"{committed.payload_hash[:12]} != replayed {actual_hash[:12]}; "
                f"producer re-executed a non-idempotent operation under "
                f"transport-level resume"
            )
        expected_next += 1
