# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-resumable-mcp-stream-and-the-server-s-event-log-cursor-has-already-been-truncated.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-resumable-mcp-stream-and-the-server-s-event-log-cursor-has-already-been-truncated.warrant.json
# Markdown SHA-256:   2cd0cf4d00a64b9fa5f23be1e2d0424415ae37e9575f779d27a12de2a5ce7cca
# Code AST SHA-256:   bc2ef603e03b20a3a9480a5d02f5e5f6f28a7b38ed24695c1572c92131353106
# Verified Classes:   StreamResumptionGapError, ResumptionState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StreamResumptionGapError(RuntimeError):
    """Raised when a resumable MCP SSE stream reconnects at a cursor the
    server cannot honor, producing a silent event gap."""


@dataclass
class ResumptionState:
    session_id: str
    last_seen_event_id: int
    tool_use_id: Optional[str] = None
    tool_result_committed: bool = False


def resume_stream(
    state: ResumptionState,
    first_event_id: int,
    first_event_type: str,
    server_retention_lower_bound: Optional[int] = None,
) -> ResumptionState:
    """Validate that a reconnected stream continues the prior episode.

    The server is NOT trusted to signal truncation. If the cursor was
    evicted, the server will typically open a fresh stream at the next
    available event with no gap indicator. We detect the gap ourselves.
    """
    expected = state.last_seen_event_id + 1

    if first_event_id != expected:
        # Two sub-cases: cursor evicted (server moved past us) or cursor
        # ahead (we advanced past what the server retained — a client bug).
        if server_retention_lower_bound is not None and \
                state.last_seen_event_id < server_retention_lower_bound:
            raise StreamResumptionGapError(
                f"session {state.session_id}: cursor {state.last_seen_event_id} "
                f"evicted (retention floor {server_retention_lower_bound}); "
                f"stream resumed at {first_event_id}. "
                f"tool_use_id={state.tool_use_id} outcome is UNKNOWN. "
                f"Must reconcile via non-streaming session/status before "
                f"exposing tool result to reasoning layer."
            )
        raise StreamResumptionGapError(
            f"session {state.session_id}: expected event {expected}, "
            f"received {first_event_id} (type={first_event_type}). "
            f"Stream is not a contiguous continuation; treat as episode "
            f"boundary and reconcile tool_use_id={state.tool_use_id}."
        )

    return ResumptionState(
        session_id=state.session_id,
        last_seen_event_id=first_event_id,
        tool_use_id=state.tool_use_id,
        tool_result_committed=state.tool_result_committed,
    )


def commit_tool_result(state: ResumptionState, event_id: int) -> ResumptionState:
    """Advance the durable cursor ONLY after the result is in memory."""
    if event_id != state.last_seen_event_id + 1:
        raise StreamResumptionGapError(
            f"refusing to commit event {event_id} after {state.last_seen_event_id}"
        )
    return ResumptionState(
        session_id=state.session_id,
        last_seen_event_id=event_id,
        tool_use_id=state.tool_use_id,
        tool_result_committed=True,
    )
