# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-a-streamable-mcp-session-across-a-transport-that-has-already-reaped-its-event-store.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-a-streamable-mcp-session-across-a-transport-that-has-already-reaped-its-event-store.warrant.json
# Markdown SHA-256:   03a749793168597dd1a36fcb08a1fa19631cb568a603059c4d6e480a226c94c2
# Code AST SHA-256:   0532ce27582f81df5c4681f987737a5fff1c0d01134d3a7999c6f93aa56972e4
# Verified Classes:   ResumeTruncationError, ResumeCheck
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class ResumeTruncationError(RuntimeError):
    """Raised when a resumed MCP stream does not begin at last_seen + 1.

    This is the client-side tripwire for the split-retention failure: the
    server accepted the session but could not honor Last-Event-ID, so the
    stream silently skipped events. Every in-flight request whose terminal
    result could have fallen in the gap must be treated as outcome-unknown.
    """


@dataclass(frozen=True)
class ResumeCheck:
    last_seen_event_id: int
    first_event_id_on_resume: int
    in_flight_request_ids: tuple[str, ...]

    def validate(self) -> None:
        expected = self.last_seen_event_id + 1
        if self.first_event_id_on_resume == expected:
            return
        if self.first_event_id_on_resume < expected:
            # Server replayed already-seen events: harmless but indicates a
            # broken cursor; still fail loud so the operator sees it.
            raise ResumeTruncationError(
                f"resume regressed: expected event {expected}, "
                f"got {self.first_event_id_on_resume} (last_seen={self.last_seen_event_id})"
            )
        # first_event_id_on_resume > expected: the gap. This is the dangerous case.
        lost = range(expected, self.first_event_id_on_resume)
        raise ResumeTruncationError(
            f"resume truncated: expected event {expected}, "
            f"got {self.first_event_id_on_resume}; "
            f"{len(lost)} events lost; "
            f"outcome-unknown requests={list(self.in_flight_request_ids)}; "
            f"do NOT retry non-idempotent calls without reconciliation"
        )


def handle_resume(
    last_seen: int,
    first_on_resume: int,
    in_flight: tuple[str, ...],
) -> None:
    """Entry point invoked by the client transport on every reconnect.

    Enforces the +1 monotonicity invariant before any event is dispatched
    to the agent. On violation, the caller must demote all in-flight
    requests to outcome-unknown and route them to reconciliation, not retry.
    """
    check = ResumeCheck(
        last_seen_event_id=last_seen,
        first_event_id_on_resume=first_on_resume,
        in_flight_request_ids=in_flight,
    )
    check.validate()


if __name__ == "__main__":
    # Observed trace: last_seen=1841, server resumed at head=1902, one
    # in-flight tools/call whose terminal result was in the gap.
    handle_resume(
        last_seen=1841,
        first_on_resume=1902,
        in_flight=("call_9f2a",),
    )
