# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-streamable-http-session-resumption-from-replaying-a-partial-tool-call-frame-into-a-fresh-sse-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-streamable-http-session-resumption-from-replaying-a-partial-tool-call-frame-into-a-fresh-sse-stream.warrant.json
# Markdown SHA-256:   c3a11d1119edc03a7cbb76e7f3935a135bc3ffe7b4a675b499ea3d517493daea
# Code AST SHA-256:   0f53aea6d7ace2844ce5ff523e27171bab038d61314948d341ad89bb24f3b114
# Verified Classes:   ResumptionFragmentError, MessageBoundaryCursor
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass, field


class ResumptionFragmentError(RuntimeError):
    """Raised when a resumed SSE stream yields a JSON-RPC fragment that does
    not begin at a message boundary. Must be handled as a transport error,
    never surfaced to the reasoning loop as a tool failure."""


@dataclass
class MessageBoundaryCursor:
    session_id: str
    last_complete_message_event_id: int = 0
    _partial_buffer: str = ""
    _in_flight_message_id: str | None = None

    def ingest_event(self, event_id: int, data: str) -> dict | None:
        """Consume one SSE event. Returns a parsed JSON-RPC message only when a
        complete message has been assembled. Advances the resumable cursor
        ONLY at message completion — this is the invariant."""
        if event_id <= self.last_complete_message_event_id:
            # Replay of an already-committed message; ignore idempotently.
            return None

        self._partial_buffer += data
        try:
            message = json.loads(self._partial_buffer)
        except json.JSONDecodeError:
            # Incomplete frame: keep buffering, do NOT advance cursor.
            return None

        # Message complete: commit boundary atomically.
        self.last_complete_message_event_id = event_id
        self._partial_buffer = ""
        self._in_flight_message_id = message.get("id")
        return message

    def resume_from(self) -> int:
        """The only value a client may send as Last-Event-ID."""
        return self.last_complete_message_event_id

    def assert_resumable(self, first_replayed_event_id: int) -> None:
        if first_replayed_event_id <= self.last_complete_message_event_id:
            return
        # A gap means the server dropped events we needed; we cannot
        # reconstruct a message boundary. Fail loudly rather than retry.
        raise ResumptionFragmentError(
            f"session {self.session_id}: replay starts at event "
            f"{first_replayed_event_id} but last committed boundary is "
            f"{self.last_complete_message_event_id}; message "
            f"{self._in_flight_message_id!r} would be corrupted"
        )
