# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-split-brain-sse-stream-when-an-mcp-session-resumes-on-a-second-http-node-mid-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-split-brain-sse-stream-when-an-mcp-session-resumes-on-a-second-http-node-mid-tool-call.warrant.json
# Markdown SHA-256:   c4512ef6ee6e0d6e497d41818e87e6370eca53edbbeafb8820f22859f630d57f
# Code AST SHA-256:   2e82972869a4c738b8853e8c854492719403a3bca312822a132af0d1caf619f1
# Verified Classes:   SessionMigrationConflict, SessionLease
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class SessionMigrationConflict(RuntimeError):
    """Raised when a resumed SSE stream cannot be served by this node
    because the in-flight execution is owned elsewhere and still live."""


@dataclass
class SessionLease:
    session_id: str
    owner_node: str
    lease_expiry: float          # monotonic seconds
    last_event_id: int
    has_terminal_event: bool


def open_resumed_stream(
    self_node: str,
    session_id: str,
    last_event_id: int,
    lease: Optional[SessionLease],
    replay_tail: int,
    now: Optional[float] = None,
) -> str:
    """Decide whether this node may open a live SSE stream for a resumed
    MCP session, or must defer. Returns a mode string; raises on the
    split-brain boundary rather than synthesizing keepalives.
    """
    now = time.monotonic() if now is None else now

    if lease is None:
        # No lease record at all: session unknown to the store.
        raise SessionMigrationConflict(
            f"no lease for session {session_id}; refusing live stream"
        )

    # Case 1: terminal event already durable past the client's cursor.
    if lease.has_terminal_event and replay_tail > last_event_id:
        return "replay_to_terminal_and_close"

    # Case 2: this node owns the live execution.
    if lease.owner_node == self_node and lease.lease_expiry >= now:
        return "live_stream"

    # Case 3: another node owns a live execution. Do NOT open a stream.
    if lease.owner_node != self_node and lease.lease_expiry >= now:
        raise SessionMigrationConflict(
            f"session {session_id} owned by {lease.owner_node} "
            f"(lease live until {lease.lease_expiry:.3f}); "
            f"client cursor {last_event_id}, replay tail {replay_tail}"
        )

    # Case 4: lease expired -> orphaned execution. Emit a terminal
    # error event so the client's turn resolves deterministically.
    return "emit_orphan_terminal_error"
