# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-last-event-id-resumption-as-unsafe-after-a-mid-stream-server-restart-and-how-does-silent.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-last-event-id-resumption-as-unsafe-after-a-mid-stream-server-restart-and-how-does-silent.warrant.json
# Markdown SHA-256:   ba493514a1fabfdcbab9aeff991a7ffcff4b3dcab385478033be0be3d50ee1c8
# Code AST SHA-256:   af8ed56e9412f99079c617fb5871532913f04e696982fae7e8d6b295d67964be
# Verified Classes:   UnverifiedResumptionError, StreamCheckpoint
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnverifiedResumptionError(RuntimeError):
    """Raised when an SSE resume cannot be proven to continue the same
    event-ID namespace. The session must not proceed as if resumed."""


@dataclass
class StreamCheckpoint:
    last_event_id: Optional[int] = None
    epoch: Optional[str] = None
    pending_tool_calls: dict = field(default_factory=dict)


def validate_resumption(
    checkpoint: StreamCheckpoint,
    first_event_id: Optional[int],
    server_epoch: Optional[str],
) -> None:
    """Called on the first event after a Last-Event-ID reconnect.

    Enforces the namespace-stability invariant: a resume is only valid if
    the incoming event ID strictly exceeds the checkpointed ID AND, when
    epochs are exposed, the epoch is unchanged.
    """
    if checkpoint.last_event_id is None:
        # No prior checkpoint; this is a fresh stream, not a resume.
        return

    if server_epoch is not None and checkpoint.epoch is not None:
        if server_epoch != checkpoint.epoch:
            raise UnverifiedResumptionError(
                f"server epoch changed {checkpoint.epoch!r} -> {server_epoch!r}; "
                f"event-ID namespace reset, resume is unsafe"
            )

    if first_event_id is None:
        raise UnverifiedResumptionError(
            "resumed stream produced an event with no id; cannot verify continuity"
        )

    if first_event_id <= checkpoint.last_event_id:
        raise UnverifiedResumptionError(
            f"first resumed event id {first_event_id} <= checkpoint "
            f"{checkpoint.last_event_id}; server likely renumbered after restart. "
            f"Mark {list(checkpoint.pending_tool_calls)} as indeterminate and "
            f"re-initialize session."
        )


def on_reconnect(checkpoint: StreamCheckpoint, first_event_id: int, server_epoch: Optional[str]) -> StreamCheckpoint:
    try:
        validate_resumption(checkpoint, first_event_id, server_epoch)
    except UnverifiedResumptionError:
        # Do not silently reset. Transition to indeterminate state so the
        # reasoning loop halts and pending calls are reconciled explicitly.
        for call_id in checkpoint.pending_tool_calls:
            checkpoint.pending_tool_calls[call_id] = "indeterminate"
        raise
    checkpoint.last_event_id = first_event_id
    if server_epoch is not None:
        checkpoint.epoch = server_epoch
    return checkpoint
