# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-resumed-sse-stream-after-mcp-session-reattachment-the-last-event-id-cursor-epoch-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-resumed-sse-stream-after-mcp-session-reattachment-the-last-event-id-cursor-epoch-invariant.warrant.json
# Markdown SHA-256:   bdde8f44432f167adb8bbc3ca909b9aeadffd7eb12721239df18b6d7519aca8d
# Code AST SHA-256:   7a3b3f4b10cb219e924597c01a98500b7004270b2be55af3aa0b79c0019a37ea
# Verified Classes:   StreamEpochViolation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class StreamEpochViolation(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot be proven continuous with the
    pre-disconnect logical execution. Transport success is NOT continuity."""
    pass


def validate_resumed_stream(
    *,
    client_session_id: str,
    server_session_id: str,
    epoch_at_disconnect: str | None,
    epoch_on_resume: str | None,
    last_recorded_seq: int,
    replayed_seqs: list[int],
    first_replayed_event_type: str,
    last_pre_disconnect_event_type: str,
) -> None:
    # Session identity must match exactly; a mismatch is a hard discontinuity.
    if client_session_id != server_session_id:
        raise StreamEpochViolation(
            f"session id mismatch: sent {client_session_id!r}, "
            f"server echoed {server_session_id!r}"
        )

    # Epoch is the load-bearing continuity proof. Missing epoch is treated as
    # rotated, never as "unchanged": the safe default is re-initialize.
    if epoch_at_disconnect is None or epoch_on_resume is None:
        raise StreamEpochViolation(
            "epoch absent on one side of resume; cannot prove logical continuity"
        )
    if epoch_at_disconnect != epoch_on_resume:
        raise StreamEpochViolation(
            f"epoch rotated across reattachment: {epoch_at_disconnect!r} -> "
            f"{epoch_on_resume!r}; session was re-instantiated"
        )

    # Sequence must be strictly monotonic and strictly past the durable cursor.
    prev = last_recorded_seq
    for seq in replayed_seqs:
        if seq <= prev:
            raise StreamEpochViolation(
                f"non-monotonic replay within epoch: seq {seq} <= cursor {prev}"
            )
        prev = seq

    # Type-level continuity: a call *start* cannot legally follow a *progress*.
    if last_pre_disconnect_event_type == "tools/call/progress" and \
       first_replayed_event_type == "tools/call/start":
        raise StreamEpochViolation(
            "replayed stream begins a new tool call immediately after "
            "mid-call progress; splice would merge unrelated executions"
        )
