# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-event-loss-when-an-mcp-streamable-http-sse-session-resumes-after-a-resource-indicator-scoped-token-rotation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-event-loss-when-an-mcp-streamable-http-sse-session-resumes-after-a-resource-indicator-scoped-token-rotation.warrant.json
# Markdown SHA-256:   eb273b7a415b86d6fba2ea988cc27ca7588a5826c95f784230909d4f1f0835c9
# Code AST SHA-256:   494c8c19d825489d9c3f951fb5a62a35cd5b769bf8e69139c8458648adf40e20
# Verified Classes:   StreamContinuityViolation, ResumeAttempt
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StreamContinuityViolation(RuntimeError):
    """Raised when an SSE resumption cannot prove contiguous replay."""


@dataclass(frozen=True)
class ResumeAttempt:
    session_id: str
    last_event_id: int          # cursor the client asked to resume from
    first_replayed_id: int      # first id actually delivered after 200 OK
    token_resource: str         # OAuth 2.1 resource indicator on the new token
    token_binding_hash: str     # server-side session partition key


def verify_resume(attempt: ResumeAttempt, *, server_declares_gap_signal: bool) -> None:
    """Enforce the contiguity invariant before trusting accumulated agent state.

    A resume is only safe if the first replayed event is exactly one past the
    cursor. Anything else is a gap: the buffer was evicted, or the token
    rotation moved the session to a fresh partition, and the agent must
    re-derive state rather than continue.
    """
    expected = attempt.last_event_id + 1

    if attempt.first_replayed_id == expected:
        return  # contiguous; safe to continue with accumulated state

    # A gap occurred. If the server cannot even signal gaps, it is not a
    # trustworthy replay source and every resume must invalidate state.
    if not server_declares_gap_signal:
        raise StreamContinuityViolation(
            f"session {attempt.session_id}: resume from {attempt.last_event_id} "
            f"delivered {attempt.first_replayed_id} with no gap-signal capability; "
            f"cannot distinguish loss from silence (resource={attempt.token_resource})"
        )

    raise StreamContinuityViolation(
        f"session {attempt.session_id}: cursor jump {attempt.last_event_id} -> "
        f"{attempt.first_replayed_id} (missing {attempt.first_replayed_id - expected} "
        f"events); token binding {attempt.token_binding_hash}; "
        f"state must be re-derived via tools/call before continuing"
    )
