# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-sse-last-event-id-resumption-from-silently-duplicating-tool-side-effects-across-an-mcp-session-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-sse-last-event-id-resumption-from-silently-duplicating-tool-side-effects-across-an-mcp-session-reconnect.warrant.json
# Markdown SHA-256:   10788bbdb70a77a014aa3550d499466dc4ed58b671e02771c062781294420ae7
# Code AST SHA-256:   789ade408a83358eb40b038ed1d1b1c557f3efc8fa9b1df37173814b63ba31a2
# Verified Classes:   ResumptionIntegrityError, BufferedEvent, StreamState, ResumableSession
# Defensive Guards:   4 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

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


class ResumptionIntegrityError(RuntimeError):
    """Raised when an SSE resume cannot be proven side-effect-safe."""
    pass


@dataclass
class BufferedEvent:
    event_id: int
    payload: str

    def fingerprint(self) -> str:
        return hashlib.sha256(f"{self.event_id}:{self.payload}".encode()).hexdigest()


@dataclass
class StreamState:
    # execution identity, minted by client in tools/call params -- NOT the cursor
    idempotency_key: str
    handler_running: bool
    committed: bool
    buffer: list[BufferedEvent] = field(default_factory=list)


class ResumableSession:
    def __init__(self) -> None:
        self._streams: dict[str, StreamState] = {}

    def resume(
        self,
        idempotency_key: str,
        last_event_id: int,
        client_seen: dict[int, str],
    ) -> list[BufferedEvent]:
        state: Optional[StreamState] = self._streams.get(idempotency_key)

        # Regime 3: buffer evicted / unknown session -> INDETERMINATE, never retry.
        if state is None:
            raise ResumptionIntegrityError(
                f"no retained buffer for idempotency_key={idempotency_key!r}; "
                "side effect is indeterminate -- do not auto-retry tools/call"
            )

        # Regime 2: handler still running -> reattach, do NOT re-execute.
        # Regime 1: handler finished -> pure replay of buffer tail.
        # Either way we replay from the buffer; we never re-invoke the handler here.
        tail = [e for e in state.buffer if e.event_id > last_event_id]

        # Invariant: first replayed id must be last_event_id + 1 (no gap, no reseed).
        if tail and tail[0].event_id != last_event_id + 1:
            raise ResumptionIntegrityError(
                f"event-id discontinuity: expected {last_event_id + 1}, "
                f"got {tail[0].event_id} -- server may have re-executed the handler"
            )

        # Invariant: overlap region must match what the client already saw.
        for ev in state.buffer:
            if ev.event_id in client_seen:
                if client_seen[ev.event_id] != ev.fingerprint():
                    raise ResumptionIntegrityError(
                        f"payload mismatch at event {ev.event_id}: "
                        "replayed bytes differ from first delivery (re-execution detected)"
                    )

        if not state.handler_running and state.committed and not tail:
            # Fully drained and committed; resume is a no-op close.
            return []

        return tail


def handle_resume(
    session: ResumableSession,
    idempotency_key: str,
    last_event_id: int,
    client_seen: dict[int, str],
) -> list[BufferedEvent]:
    events = session.resume(idempotency_key, last_event_id, client_seen)
    if events and events[0].event_id != last_event_id + 1:
        # Defensive re-check; resume() already enforces this.
        raise ResumptionIntegrityError("post-resume cursor invariant violated")
    return events
