# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-forked-mcp-session-when-a-resumable-sse-stream-is-re-attached-across-a-load-balanced-edge-that-has-already-repl.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-forked-mcp-session-when-a-resumable-sse-stream-is-re-attached-across-a-load-balanced-edge-that-has-already-repl.warrant.json
# Markdown SHA-256:   77586c36be021e3613ecdad76328ad970fbe100e2621e61f824645455e8db6e7
# Code AST SHA-256:   5b03d5d76c21b1b6844a9f0620bc7a8823cd491ab93fa654c7cc6ab8cb819f7a
# Verified Classes:   SessionForkDetected
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SessionForkDetected(RuntimeError):
    """Raised when a resumable MCP stream re-attaches to a session whose
    event-log provenance cannot be proven, i.e. the session identity forked
    across replicas and terminal results may be lost while side effects
    may be duplicated."""


def validate_resumption(
    sent_session_id: str,
    sent_last_event_id: int,
    response_session_id: str,
    first_replayed_event_id: int | None,
    unacked_terminal_calls: list[str],
) -> None:
    """Enforce the resumption provenance invariant before the agent loop
    is allowed to continue on a re-attached SSE stream.

    Raises SessionForkDetected on any condition where the client cannot
    prove that the stream it is now reading is the continuation of the
    one it left.
    """
    # 1. Session identity must not change under a resumption request.
    if response_session_id != sent_session_id:
        raise SessionForkDetected(
            f"session id changed on resume: sent={sent_session_id!r} "
            f"got={response_session_id!r}; terminal calls at risk: "
            f"{unacked_terminal_calls!r}"
        )

    # 2. If any event was replayed, it must be strictly after the cursor
    #    and contiguous with it. A gap means a hole in the log; a
    #    duplicate means the cursor was already consumed.
    if first_replayed_event_id is not None:
        if first_replayed_event_id <= sent_last_event_id:
            raise SessionForkDetected(
                f"duplicate replay: cursor={sent_last_event_id} "
                f"first_event={first_replayed_event_id}"
            )
        if first_replayed_event_id != sent_last_event_id + 1:
            raise SessionForkDetected(
                f"event-log gap: cursor={sent_last_event_id} "
                f"first_event={first_replayed_event_id}"
            )

    # 3. If the stream is live but we hold unacknowledged terminal calls
    #    and no replay was offered, the terminal result may have been
    #    emitted by a replica we are no longer talking to. Do not resume
    #    the loop; re-drive via idempotency keys instead.
    if first_replayed_event_id is None and unacked_terminal_calls:
        raise SessionForkDetected(
            "live stream with no replay while terminal calls are "
            f"unacknowledged: {unacked_terminal_calls!r}; "
            "outcome is UNKNOWN, re-drive with idempotency keys"
        )
