# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-sse-resume-has-silently-re-bound-to-a-new-logical-session-rather-than-the-one-it-left.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-sse-resume-has-silently-re-bound-to-a-new-logical-session-rather-than-the-one-it-left.warrant.json
# Markdown SHA-256:   2c9f2caabbf36a59c05510766ce3170053551c0094e1192fcaf897db0ba2c61d
# Code AST SHA-256:   7cdf2259bcd28ff31eddfa049c674a6689c1373489ae650cc5b2acd19f482c7a
# Verified Classes:   SessionForkedError, SessionDeadError, ResumeProbe
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field
from typing import Optional


class SessionForkedError(RuntimeError):
    """Raised when an SSE resume reattaches to a different logical session
    generation than the one that emitted the pre-drop event tail."""


class SessionDeadError(RuntimeError):
    """Raised when the server refuses reattachment (404/410) — the session
    must be re-initialized, not retried."""


@dataclass
class ResumeProbe:
    """Client-side invariant check for MCP HTTP-native SSE resumption.

    The client plants a session-scoped nonce at initialize time and echoes it
    on every resume. A server that forked onto a cold replica cannot return
    the nonce, because the nonce lives in the volatile session state that the
    fork did not carry. This is the cheapest observable proxy for the
    generation-pinning invariant.
    """

    session_id: str
    planted_nonce: str
    last_event_id: int
    applied_event_ids: set = field(default_factory=set)
    dedup_window: int = 256

    def _nonce_ok(self, echoed: Optional[str]) -> bool:
        if echoed is None:
            return False
        return hashlib.sha256(echoed.encode()).digest() == hashlib.sha256(
            self.planted_nonce.encode()
        ).digest()

    def verify_resume(
        self,
        http_status: int,
        echoed_nonce: Optional[str],
        replayed_event_ids: list,
    ) -> None:
        if http_status in (404, 410):
            raise SessionDeadError(
                f"session {self.session_id} refused reattachment "
                f"(status {http_status}); re-initialize required"
            )
        if http_status != 200:
            raise SessionForkedError(
                f"unexpected resume status {http_status} for {self.session_id}"
            )
        if not self._nonce_ok(echoed_nonce):
            raise SessionForkedError(
                f"resume for {self.session_id} landed on a generation that "
                f"cannot echo the planted nonce; cached handles and "
                f"subscriptions are invalid"
            )
        # Replay is at-least-once: dedup against the client's applied set.
        fresh = [e for e in replayed_event_ids if e not in self.applied_event_ids]
        if len(self.applied_event_ids) > self.dedup_window:
            # Keep the window bounded; drop oldest by insertion order.
            excess = len(self.applied_event_ids) - self.dedup_window
            for _ in range(excess):
                self.applied_event_ids.pop()
        self.applied_event_ids.update(fresh)
        if fresh:
            self.last_event_id = max(fresh)


def resume_stream(probe: ResumeProbe, transport) -> list:
    """Attempt a resumable SSE reattachment and enforce the invariant."""
    resp = transport.resume(
        session_id=probe.session_id,
        last_event_id=probe.last_event_id,
        nonce_echo=probe.planted_nonce,
    )
    probe.verify_resume(
        http_status=resp.status,
        echoed_nonce=resp.echoed_nonce,
        replayed_event_ids=resp.event_ids,
    )
    return resp.events
