# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-replay-divergence-when-a-streamable-http-mcp-server-resumes-a-broken-sse-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-replay-divergence-when-a-streamable-http-mcp-server-resumes-a-broken-sse-stream.warrant.json
# Markdown SHA-256:   b8d55fe07e54c95cc15f4e8e10813945141c527695cdf41a7488d357e7ff8b25
# Code AST SHA-256:   69bc62e76dbbf186249c529b4831ffc58c3d6ded29d9c28f7ea40e32e490250a
# Verified Classes:   StreamContinuityViolation, ResumeProbe
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class StreamContinuityViolation(RuntimeError):
    """Raised when a resumed SSE stream cannot be proven continuous with its anchor."""


@dataclass(frozen=True)
class ResumeProbe:
    last_event_id: int | None
    first_event_id: int | None
    status: int
    anchor_resolvable: bool


def assert_resume_is_continuous(probe: ResumeProbe) -> None:
    # No anchor: fresh subscribe, any 200 stream is fine.
    if probe.last_event_id is None:
        if probe.status != 200:
            raise StreamContinuityViolation(
                f"fresh subscribe expected 200, got {probe.status}"
            )
        return

    # Anchor present but server cannot locate it: a 200 here is the silent-loss bug.
    if not probe.anchor_resolvable:
        if probe.status == 200:
            raise StreamContinuityViolation(
                f"server returned 200 on unresolvable Last-Event-ID "
                f"{probe.last_event_id}; must be 404/409 to force re-init"
            )
        if probe.status not in (400, 404, 409):
            raise StreamContinuityViolation(
                f"unresolvable anchor produced unexpected status {probe.status}"
            )
        return

    # Anchor resolvable: the resumed stream must start strictly after it.
    if probe.status != 200:
        raise StreamContinuityViolation(
            f"resolvable anchor {probe.last_event_id} but status {probe.status}"
        )
    if probe.first_event_id is None:
        raise StreamContinuityViolation(
            f"resumed stream for anchor {probe.last_event_id} opened with no events "
            f"(silent hang: client cannot distinguish 'caught up' from 'lost')"
        )
    if probe.first_event_id <= probe.last_event_id:
        raise StreamContinuityViolation(
            f"replay divergence: first event {probe.first_event_id} <= anchor "
            f"{probe.last_event_id}; client dedup would drop a real event"
        )


def run_conformance(cases: list[ResumeProbe]) -> None:
    for i, probe in enumerate(cases):
        try:
            assert_resume_is_continuous(probe)
        except StreamContinuityViolation as exc:
            raise StreamContinuityViolation(f"case {i}: {exc}") from exc
