# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-mcp-stream-resumed-sse-replay-before-applying-it-to-agent-state.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-mcp-stream-resumed-sse-replay-before-applying-it-to-agent-state.warrant.json
# Markdown SHA-256:   51f2608829cbbe8bf882ef78aa80d27830eef591601d55b4a776e3367e65fe93
# Code AST SHA-256:   3400c70a21202bbdbd257fbdb0e9251c4a7ca39ea47c161721e9cdc8940e6c63
# Verified Classes:   ReplayContinuityViolation, StreamState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ReplayContinuityViolation(RuntimeError):
    """Raised when an MCP SSE replay cannot be safely applied to agent state."""
    pass


class StreamState:
    def __init__(self, committed_id: int = 0):
        self.committed_id = committed_id
        self.last_seen_id = committed_id
        self.in_flight_event_id = None  # set when dispatch begins, cleared on commit

    def on_event_received(self, event_id: int):
        # Transport cursor advances on receipt, independent of commitment.
        self.last_seen_id = event_id
        self.in_flight_event_id = event_id

    def commit(self, event_id: int):
        if event_id != self.committed_id + 1:
            raise ReplayContinuityViolation(
                f"non-contiguous commit: committed={self.committed_id} got={event_id}"
            )
        self.committed_id = event_id
        self.in_flight_event_id = None


def apply_replay(state: StreamState, replayed_events, is_idempotent):
    """Apply a resumed SSE replay against committed state, not transport cursor."""
    for ev in replayed_events:
        if ev.id <= state.committed_id:
            continue  # already committed; discard duplicate delivery
        if ev.id > state.committed_id + 1:
            raise ReplayContinuityViolation(
                f"gap in replay: committed={state.committed_id} next={ev.id}; "
                "refuse apply, fall back to checkpoint recovery"
            )
        interrupted = state.in_flight_event_id == ev.id
        if interrupted and not is_idempotent(ev.id):
            raise ReplayContinuityViolation(
                f"replayed event {ev.id} may be partially applied and is not "
                "idempotent; refuse apply, fall back to checkpoint recovery"
            )
        dispatch_and_commit(state, ev)


def dispatch_and_commit(state: StreamState, ev):
    # ... apply payload (tool call, memory write) ...
    state.commit(ev.id)
