# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-session-resumption-from-silently-forking-an-mcp-agent-s-tool-call-state-across-sse-replay-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-session-resumption-from-silently-forking-an-mcp-agent-s-tool-call-state-across-sse-replay-boundaries.warrant.json
# Markdown SHA-256:   9acc0abf33eaaadb18e8bbe71faa511c7282b3578f84a0a6f7382baf5427ff0e
# Code AST SHA-256:   89cdf8cba4c42cd13f5e1036425df5233cdecb704833dea27394d51b7861c35d
# Verified Classes:   SessionEpochMismatch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SessionEpochMismatch(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot prove causal continuity
    with the client's pre-disconnect state. The client MUST re-initialize
    rather than replay, to avoid duplicate tool-call dispatch."""
    pass


def resume_stream(
    last_event_id: int,
    client_epoch: str,
    server_epoch: str,
    outstanding_call_ids: set[str],
    server_known_call_ids: set[str],
) -> int:
    """Validate that a resumed SSE stream is causally continuous with the
    client's pre-disconnect state. Returns the cursor to resume from, or
    raises SessionEpochMismatch to force re-initialization."""

    if client_epoch != server_epoch:
        # Capability snapshot or session identity diverged across shards.
        raise SessionEpochMismatch(
            f"epoch mismatch: client={client_epoch!r} server={server_epoch!r}; "
            f"refusing replay, re-initialize required"
        )

    # Even with matching epochs, the server must know about every in-flight
    # call the client believes is outstanding. An unknown call_id means the
    # server has no handler state for it -> replay would fork execution.
    orphans = outstanding_call_ids - server_known_call_ids
    if orphans:
        raise SessionEpochMismatch(
            f"server has no state for in-flight call_ids {sorted(orphans)}; "
            f"replay would re-dispatch them, refusing"
        )

    # Cursor is causally dense and session identity is continuous: safe.
    return last_event_id + 1
