# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-resumption-replay-divergence-across-stateless-mcp-streamable-sse-replicas.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-resumption-replay-divergence-across-stateless-mcp-streamable-sse-replicas.warrant.json
# Markdown SHA-256:   d3cfede0988f31450df235cad84f4416f147db61b11400c7620a3e68dd11b586
# Code AST SHA-256:   d838b990313f79d9036e319886d76624f957765f470eb69fd5c2c10c1224216d
# Verified Classes:   ResumptionDivergenceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ResumptionDivergenceError(RuntimeError):
    """Raised when a resume request cannot be satisfied without risking
    duplicate side effects or a spliced event sequence."""
    pass


def resume_stream(session_id: str, last_event_id: str, event_log, checkpoint_store):
    seq = parse_seq(last_event_id)  # "sess:7" -> (sess, 7); raises on malformed

    # Invariant 1: identity must be session-scoped and match this session.
    if seq.session != session_id:
        raise ResumptionDivergenceError(
            f"Last-Event-ID {last_event_id!r} belongs to session {seq.session!r}, "
            f"not {session_id!r}; refusing to splice streams."
        )

    # Invariant 2: the event must actually exist in the durable log.
    if not event_log.contains(session_id, seq.n):
        # Cold replica / expired TTL / forged id. Do NOT fall back to re-run:
        # the client will append, producing evt-1..6 + evt-1'..N'.
        raise ResumptionDivergenceError(
            f"No durable record of {last_event_id!r} for session {session_id!r}; "
            f"cannot prove emission. Client must restart with a new session."
        )

    # Invariant 3: the checkpoint at that boundary must be intact so that
    # re-emitting seq+1.. does not re-fire committed side effects.
    if not checkpoint_store.is_intact(session_id, seq.n):
        raise ResumptionDivergenceError(
            f"Checkpoint for {last_event_id!r} missing or torn; "
            f"re-execution would duplicate side effects."
        )

    # Sound path: continue strictly after the proven boundary.
    return event_log.stream_after(session_id, seq.n)
