# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-resume-an-mcp-streamable-http-session-after-an-sse-to-post-migration-and-how-does-the-last-event-id-curso.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-resume-an-mcp-streamable-http-session-after-an-sse-to-post-migration-and-how-does-the-last-event-id-curso.warrant.json
# Markdown SHA-256:   3344c4c8b38638f8aa3eb68c035acf897d388e8cf1e9ece08896aaf9f9c85a07
# Code AST SHA-256:   6ebb21f9aae39a1a88c24b32b95908e305c21d90a41f2b1893223048b9370cd1
# Verified Classes:   UnsoundResumptionError, SessionResumeGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnsoundResumptionError(RuntimeError):
    """Raised when a client attempts Last-Event-ID resumption across a POST-mutation gap."""
    pass


class SessionResumeGuard:
    def __init__(self, session_id: str):
        self.session_id = session_id
        self.last_applied_event_id: int | None = None
        self.post_mutations_since_cursor: int = 0

    def on_event_applied(self, event_id: int) -> None:
        # Advancing the SSE cursor resets the POST-gap counter only if no
        # POST mutation has been applied since the prior cursor.
        if self.post_mutations_since_cursor != 0:
            # Cursor advanced but POST effects are still unrepresented in the
            # event log: the watermark is no longer a true prefix.
            raise UnsoundResumptionError(
                f"session {self.session_id}: event {event_id} applied while "
                f"{self.post_mutations_since_cursor} POST mutations are outside "
                "the event log; cursor is not a total-order watermark"
            )
        self.last_applied_event_id = event_id

    def on_post_mutation(self) -> None:
        self.post_mutations_since_cursor += 1

    def attempt_resume(self, presented_last_event_id: int) -> str:
        if presented_last_event_id != self.last_applied_event_id:
            raise UnsoundResumptionError(
                f"session {self.session_id}: presented Last-Event-ID "
                f"{presented_last_event_id} != applied {self.last_applied_event_id}"
            )
        if self.post_mutations_since_cursor > 0:
            # The cursor is syntactically valid but semantically behind the
            # POST-applied state. Replay would re-deliver events whose effects
            # the client already holds. Refuse and re-initialize.
            raise UnsoundResumptionError(
                f"session {self.session_id}: {self.post_mutations_since_cursor} "
                "POST-driven mutations are not represented in the SSE log; "
                "Last-Event-ID replay is unsound, re-initialize session"
            )
        return "resume"
