# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-resumption-as-a-lossy-reattachment-rather-than-a-transparent-continuation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-resumption-as-a-lossy-reattachment-rather-than-a-transparent-continuation.warrant.json
# Markdown SHA-256:   717dd46a70bf421d0c69843f3fbee769a3a79cf85f2b0ec6b66a2aca57b4c995
# Code AST SHA-256:   4ded3e6006f07bd59db5d1f307ee5094b4eaf0be893a7174cfef4f989cf2f5dc
# Verified Classes:   StreamResumptionGapError, SessionWatermark
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class StreamResumptionGapError(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot be proven contiguous
    with the client's committed-event watermark, i.e. the replay buffer
    window no longer covers the client's Last-Event-ID."""


@dataclass
class SessionWatermark:
    session_id: str
    committed_event_id: int = 0          # highest event whose side effects are durable
    received_event_id: int = 0           # highest event merely observed
    executed_keys: set[str] = field(default_factory=set)


def _idempotency_key(event_id: int, payload: bytes) -> str:
    return hashlib.sha256(f"{event_id}:".encode() + payload).hexdigest()


def resume_stream(
    wm: SessionWatermark,
    last_event_id: int,
    oldest_retained_id: int | None,
    replayed_events: list[tuple[int, bytes]],
    execute_side_effect,
) -> None:
    """Reattach to a resumed MCP stream under lossy-reattachment semantics.

    Raises StreamResumptionGapError if contiguity cannot be proven, so the
    caller reconciles state instead of silently continuing reasoning.
    """
    # 1. Buffer-window check: can the server even honor our Last-Event-ID?
    if oldest_retained_id is None:
        raise StreamResumptionGapError(
            f"session {wm.session_id}: server exposed no buffer window; "
            f"cannot prove Last-Event-ID {last_event_id} is replayable"
        )
    if last_event_id < oldest_retained_id - 1:
        raise StreamResumptionGapError(
            f"session {wm.session_id}: Last-Event-ID {last_event_id} precedes "
            f"oldest retained {oldest_retained_id}; events "
            f"{last_event_id + 1}..{oldest_retained_id - 1} are lost"
        )

    # 2. Contiguity check: replay must be exactly contiguous from watermark.
    expected = last_event_id + 1
    for event_id, payload in replayed_events:
        if event_id != expected:
            raise StreamResumptionGapError(
                f"session {wm.session_id}: non-contiguous replay, expected "
                f"{expected}, got {event_id}; stream has a hole"
            )
        expected += 1

        # 3. Replay dedup: never re-execute a committed side effect.
        key = _idempotency_key(event_id, payload)
        if event_id <= wm.committed_event_id or key in wm.executed_keys:
            wm.received_event_id = max(wm.received_event_id, event_id)
            continue

        execute_side_effect(event_id, payload)
        wm.executed_keys.add(key)
        wm.committed_event_id = event_id
        wm.received_event_id = max(wm.received_event_id, event_id)
