# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-stream-resumption-as-a-replay-safety-problem-rather-than-a-transport-retry-problem.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-stream-resumption-as-a-replay-safety-problem-rather-than-a-transport-retry-problem.warrant.json
# Markdown SHA-256:   2144993c171edb43f76fba1c36188e74d68e4b8753ad496644eb278bf61fe5f7
# Code AST SHA-256:   171cca95e96ede72c83ba318d113f7520a31d53613f02926f0c24a36d878b249
# Verified Classes:   StreamResumeContinuityError, ResumeState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class StreamResumeContinuityError(RuntimeError):
    """Raised when a resumed MCP stream cannot be certified as contiguous
    and replay-safe, so the instance must not advance dependent state."""


@dataclass
class ResumeState:
    last_processed_id: int
    processed_ids: set[int] = field(default_factory=set)
    gap_ledger: list[tuple[int, int]] = field(default_factory=list)


def reconcile_resume(
    state: ResumeState,
    earliest_available_id: int | None,
    first_resumed_id: int,
) -> ResumeState:
    """Validate a stream resume against the replay-safety invariant.

    Two independent hazards must be checked:
      1. Gap: earliest_available_id > last_processed_id + 1 means events
         were evicted and are permanently lost.
      2. Replay: first_resumed_id <= last_processed_id means events the
         instance already acted on will be re-delivered.
    """
    if earliest_available_id is None:
        # Server did not certify its lower bound; we cannot distinguish a
        # clean resume from a silent gap. Refuse to trust continuity.
        raise StreamResumeContinuityError(
            "server did not report earliest_available_id; "
            "resume cannot be certified contiguous"
        )

    if earliest_available_id > state.last_processed_id + 1:
        # Silent gap: events in [last_processed_id+1, earliest_available_id-1]
        # are gone. Record it; do not treat the stream as contiguous.
        state.gap_ledger.append(
            (state.last_processed_id + 1, earliest_available_id - 1)
        )
        # A gap is recoverable only via out-of-band state reconciliation.
        # The instance must not advance continuity-dependent state here.
        raise StreamResumeContinuityError(
            f"replay gap: events {state.last_processed_id + 1}"
            f"..{earliest_available_id - 1} permanently lost; "
            "downstream continuity must be re-established out of band"
        )

    if first_resumed_id <= state.last_processed_id:
        # Replay window overlaps already-processed events. This is safe
        # ONLY if the consumer deduplicates by ID before side effects.
        # We surface it so the caller routes through the dedup path.
        if first_resumed_id not in state.processed_ids and first_resumed_id != state.last_processed_id:
            raise StreamResumeContinuityError(
                f"replay begins at {first_resumed_id} but that id was never "
                "processed; processed-set is inconsistent with high-water mark"
            )

    return state


def apply_event(state: ResumeState, event_id: int, side_effect) -> ResumeState:
    """Apply an event exactly once, deduplicating replays by ID."""
    if event_id in state.processed_ids:
        return state  # replay of an already-applied event: no-op
    if event_id <= state.last_processed_id:
        raise StreamResumeContinuityError(
            f"event {event_id} arrives below high-water mark "
            f"{state.last_processed_id} but is not in processed-set; "
            "cannot prove it was applied"
        )
    side_effect(event_id)
    state.processed_ids.add(event_id)
    state.last_processed_id = event_id
    return state
