# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-streamable-http-session-as-non-resumable-after-a-mid-stream-disconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-streamable-http-session-as-non-resumable-after-a-mid-stream-disconnect.warrant.json
# Markdown SHA-256:   256b63ea11a8ac95850eb4c3ff7ea0066a192b727740eb542bfb5565ee9ac2f8
# Code AST SHA-256:   ca402c45ea4543150da82f2baed9e8e5a55fa8beca2e44264e86bd8a78d40a2b
# Verified Classes:   ResumptionGapError, NonResumableOperationError, StreamAccumulator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ResumptionGapError(RuntimeError):
    """Raised when a resumed SSE stream does not continue contiguously from the last cursor."""
    pass


class NonResumableOperationError(RuntimeError):
    """Raised when resumption is attempted on a non-idempotent in-flight tool call."""
    pass


@dataclass
class StreamAccumulator:
    session_id: str
    request_id: str
    last_event_id: int = -1
    chunks: list = field(default_factory=list)
    idempotent: bool = False
    replay_window: int | None = None

    def resume(self, first_event_id: int, payload: str) -> None:
        # Idempotency gate: never resume a mutating call, even contiguously.
        if not self.idempotent:
            raise NonResumableOperationError(
                f"request {self.request_id} is not idempotent; "
                f"resumption unsafe, reconcile via idempotency key instead"
            )
        # Contiguity gate: the only correct resumption is exact successor.
        if first_event_id != self.last_event_id + 1:
            gap = first_event_id - self.last_event_id - 1
            raise ResumptionGapError(
                f"session {self.session_id} cursor miss: expected id "
                f"{self.last_event_id + 1}, got {first_event_id} "
                f"(gap of {gap} events); discard partial accumulation"
            )
        # Replay-window gate: even a contiguous resume is untrustworthy
        # if the server's buffer is bounded and may have wrapped.
        if self.replay_window is not None and len(self.chunks) >= self.replay_window:
            raise ResumptionGapError(
                f"session {self.session_id} accumulation exceeds replay_window "
                f"{self.replay_window}; cursor may alias a wrapped buffer"
            )
        self.chunks.append(payload)
        self.last_event_id = first_event_id

    def digest(self) -> str:
        return hashlib.sha256("".join(self.chunks).encode()).hexdigest()


def handle_reconnect(acc: StreamAccumulator, first_event_id: int, payload: str) -> str:
    try:
        acc.resume(first_event_id, payload)
    except (ResumptionGapError, NonResumableOperationError):
        # Correct boundary action: cancel the original request and re-issue,
        # never splice a gapped stream into the agent's reasoning context.
        raise
    return acc.digest()
