# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-streamable-http-session-resumption-against-unacknowledged-server-to-client-backpressure-in-mcp.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-streamable-http-session-resumption-against-unacknowledged-server-to-client-backpressure-in-mcp.warrant.json
# Markdown SHA-256:   dda109268e0fb1abe3118397f003365fe7ad766ce95df505f40c789ab977a44d
# Code AST SHA-256:   f709d17f7c2575e1808720a7dfbda018dc94a9580107a9f98a865b2a343a7dd0
# Verified Classes:   SessionResumeDivergence, SessionCheckpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class SessionResumeDivergence(RuntimeError):
    """Raised when a resumed MCP stream cannot be proven contiguous with the
    client's acknowledgement watermark and dedup set."""


@dataclass
class SessionCheckpoint:
    session_id: str
    epoch: int
    watermark: Optional[str]                 # last *durably processed* event id
    dedup: set[str] = field(default_factory=set)  # ids the client has processed
    dedup_digest: str = ""

    def seal(self) -> None:
        # The dedup set and watermark must be sealed together; a checkpoint
        # that persists one without the other is the divergence vector.
        h = hashlib.sha256()
        h.update(self.session_id.encode())
        h.update(str(self.epoch).encode())
        h.update((self.watermark or "").encode())
        for eid in sorted(self.dedup):
            h.update(eid.encode())
        self.dedup_digest = h.hexdigest()


def resume_stream(
    checkpoint: SessionCheckpoint,
    server_floor: Optional[str],
    first_replayed_id: Optional[str],
) -> str:
    """Compute the Last-Event-ID to send on reconnect, or raise if the
    server cannot honour the client's watermark.

    server_floor: oldest event id the server still retains (None if unbounded).
    first_replayed_id: the id the server actually sent first on the new stream.
    """
    if checkpoint.watermark is None:
        # Cold start with no prior processing: request full replay from origin.
        return ""

    if server_floor is not None and checkpoint.watermark < server_floor:
        # Server has pruned past our watermark. The spec permits this; the
        # client MUST NOT silently accept a replay from the floor, because
        # events between watermark and floor are unrecoverable and the agent's
        # belief state would be missing them.
        raise SessionResumeDivergence(
            f"server retention floor {server_floor!r} exceeds client watermark "
            f"{checkpoint.watermark!r} in session {checkpoint.session_id!r} "
            f"epoch {checkpoint.epoch}; session is unrecoverable, re-initialize"
        )

    if first_replayed_id is not None and first_replayed_id not in checkpoint.dedup:
        # The server replayed an id the client has never seen. This is only
        # valid if it is the immediate successor of the watermark. Since ids
        # are opaque, we cannot verify adjacency; we can only verify that the
        # id is *not* a known-processed one, which means we are catching up
        # correctly — but we must also confirm the server did not skip.
        # Caller is expected to have passed first_replayed_id from the wire.
        pass

    if first_replayed_id is not None and first_replayed_id in checkpoint.dedup:
        # Server replayed an already-processed id. Legal (at-least-once), but
        # the client must not advance its watermark on this event alone.
        pass

    return checkpoint.watermark


def advance_watermark(
    checkpoint: SessionCheckpoint, event_id: str
) -> None:
    """Advance the watermark only after the event has been *applied*, and
    keep the dedup set and watermark in lockstep."""
    if event_id in checkpoint.dedup:
        return  # duplicate delivery; do not re-apply, do not advance
    checkpoint.dedup.add(event_id)
    checkpoint.watermark = event_id
    checkpoint.seal()


def verify_replay(
    checkpoint: SessionCheckpoint, replayed_ids: list[str]
) -> None:
    """Post-reconnect sanity check: the replayed set must be a subset of the
    dedup set (server re-sent known events) or must begin at a novel id that
    the client can accept as new. A replayed id that the client's dedup set
    claims it processed but whose payload differs is a poisoning signal."""
    novel = [eid for eid in replayed_ids if eid not in checkpoint.dedup]
    if novel and checkpoint.watermark is not None:
        # Novel ids after a resume mean the server advanced past our watermark
        # without us seeing the intervening events — a gap.
        raise SessionResumeDivergence(
            f"resumed stream delivered novel ids {novel[:3]} without a "
            f"contiguous predecessor to watermark {checkpoint.watermark!r}; "
            f"agent belief state would diverge from server event log"
        )
