Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

36.5 KB
Raw Blame
from __future__ import annotations

import asyncio
import sys
from textwrap import dedent
from typing import TYPE_CHECKING
from unittest.mock import AsyncMock, MagicMock, Mock

import pytest

from marimo._config.manager import get_default_config_manager
from marimo._server.lsp import LspServer
from marimo._server.session.listeners import RecentsTrackerListener
from marimo._server.session_manager import SessionManager
from marimo._server.tokens import AuthToken, SkewProtectionToken
from marimo._server.workspace import NEW_FILE, EmptyWorkspace, infer_workspace
from marimo._session import (
    KernelManager,
    Session,
)
from marimo._session.consumer import SessionConsumer
from marimo._session.model import ConnectionState, SessionMode
from marimo._session.notebook import AppFileManager
from marimo._session.room import Room
from marimo._types.ids import SessionId

if TYPE_CHECKING:
    from collections.abc import Iterator
    from pathlib import Path


@pytest.fixture(autouse=True)
def _preserve_main_module() -> Iterator[None]:
    """Restore sys.modules["__main__"] after each test.

    Earlier tests (e.g. in test_asgi.py) may start kernel threads in RUN
    mode that call patch_main_module(), permanently replacing __main__
    with a module whose __file__ points to a now-deleted temp file.
    On Windows the multiprocessing 'spawn' start method reads
    __main__.__file__ to bootstrap the child process, so a stale path
    causes FileNotFoundError and the parent hangs on listener.accept().
    """
    saved = sys.modules["__main__"]
    yield
    sys.modules["__main__"] = saved


@pytest.fixture
def mock_session_consumer():
    mock = Mock(spec=SessionConsumer)
    mock.consumer_id = "test_consumer_id"
    return mock


@pytest.fixture
def mock_session():
    session = Mock(spec=Session)
    session.initialization_id = "test_init_id"
    session.session_cache_manager = None
    session.room = Room()
    session.connect_consumer.side_effect = session.room.add_consumer
    session.connection_state.return_value = ConnectionState.OPEN
    session.kernel_manager = Mock(spec=KernelManager)
    session.kernel_manager.kernel_task = None
    return session


@pytest.fixture
def session_manager():
    return SessionManager(
        workspace=EmptyWorkspace(),
        mode=SessionMode.EDIT,
        quiet=False,
        include_code=True,
        lsp_server=MagicMock(spec=LspServer),
        config_manager=get_default_config_manager(current_path=None),
        cli_args={},
        argv=None,
        auth_token=None,
        redirect_console_to_browser=False,
        ttl_seconds=None,
    )


def add_session(
    manager: SessionManager, session_id: SessionId, session: Session
) -> None:
    """Add a session to the manager (for tests)."""
    manager._repository.add_sync(session_id, session)


session_id = SessionId("test_session_id")


async def test_start_lsp_server(session_manager: SessionManager) -> None:
    await session_manager.start_lsp_server()
    session_manager.lsp_server.start.assert_called_once()


async def test_create_session_new(
    session_manager: SessionManager, mock_session_consumer: SessionConsumer
) -> None:
    session = await session_manager.create_session(
        session_id,
        mock_session_consumer,
        query_params={},
        file_key=NEW_FILE,
        auto_instantiate=False,
        main=True,
    )
    assert session_id in session_manager.sessions
    assert session_manager.get_session(session_id) is session
    # Close ourselves to finish the test
    session.close()


async def test_create_session_absolute_url(
    session_manager: SessionManager,
    mock_session_consumer: SessionConsumer,
    temp_marimo_file: str,
) -> None:
    session = await session_manager.create_session(
        session_id,
        mock_session_consumer,
        query_params={},
        file_key=temp_marimo_file,
        auto_instantiate=False,
        main=True,
    )
    assert session_id in session_manager.sessions
    assert session_manager.get_session(session_id) is session
    # Close ourselves to finish the test
    session.close()


def test_maybe_resume_session_for_new_file(
    session_manager: SessionManager,
    mock_session: Session,
) -> None:
    mock_session.connection_state.return_value = ConnectionState.ORPHANED
    mock_session.app_file_manager = AppFileManager(filename=None)
    session_manager.sessions[session_id] = mock_session

    # Resume the same session_id with a new file -> doesn't match
    resumed_session = session_manager.maybe_resume_session(
        session_id, NEW_FILE
    )
    assert resumed_session is None

    # Resume the same session_id with a different file -> doesn't match
    # This is technically a bad state and should be unreachable
    resumed_session = session_manager.maybe_resume_session(
        session_id, "different_file.py"
    )
    assert resumed_session is None

    # Resume with a different session_id -> doesn't match
    resumed_session = session_manager.maybe_resume_session(
        "different_session_id", NEW_FILE
    )
    assert resumed_session is None


def test_maybe_resume_session_for_existing_file(
    session_manager: SessionManager,
    mock_session: Session,
    temp_marimo_file: str,
) -> None:
    mock_session.connection_state.return_value = ConnectionState.ORPHANED
    mock_session.app_file_manager = AppFileManager(filename=temp_marimo_file)
    add_session(session_manager, session_id, mock_session)

    # Resume the same session_id with the same file -> matches
    resumed_session = session_manager.maybe_resume_session(
        session_id, temp_marimo_file
    )
    assert resumed_session is mock_session

    # Resume the same session_id with a different file -> doesn't match
    # This is technically a bad state and should be unreachable
    resumed_session = session_manager.maybe_resume_session(
        session_id, "different_file.py"
    )
    assert resumed_session is None

    # Resume with a different session_id -> matches
    resumed_session = session_manager.maybe_resume_session(
        "different_session_id", temp_marimo_file
    )
    assert resumed_session is mock_session


def test_close_session(
    session_manager: SessionManager, mock_session: Session
) -> None:
    mock_session.app_file_manager = AppFileManager(filename=None)
    add_session(session_manager, session_id, mock_session)
    assert session_manager.close_session(session_id)
    assert session_id not in session_manager.sessions
    mock_session.close.assert_called_once()


def test_any_clients_connected_new_file(
    session_manager: SessionManager, mock_session: Session
) -> None:
    add_session(session_manager, session_id, mock_session)
    mock_session.app_file_manager = AppFileManager(filename=None)
    assert session_manager.any_clients_connected(NEW_FILE) is False
    assert session_manager.any_clients_connected("different_file.py") is False


def test_any_clients_connected_existing_file(
    session_manager: SessionManager,
    mock_session: Session,
    temp_marimo_file: str,
) -> None:
    add_session(session_manager, session_id, mock_session)
    mock_session.app_file_manager = AppFileManager(filename=temp_marimo_file)
    assert session_manager.any_clients_connected(NEW_FILE) is False
    assert session_manager.any_clients_connected(temp_marimo_file) is True
    assert session_manager.any_clients_connected("different_file.py") is False


def test_close_all_sessions(
    session_manager: SessionManager, mock_session: Session
) -> None:
    add_session(session_manager, SessionId("session1"), mock_session)
    add_session(session_manager, SessionId("session2"), mock_session)
    session_manager.close_all_sessions()
    assert len(session_manager.sessions) == 0
    assert mock_session.close.call_count == 2


async def test_shutdown(
    session_manager: SessionManager, mock_session: Session
) -> None:
    add_session(session_manager, SessionId("session1"), mock_session)
    add_session(session_manager, SessionId("session2"), mock_session)

    await session_manager.shutdown()
    session_manager.lsp_server.stop.assert_called_once()
    assert len(session_manager.sessions) == 0
    assert mock_session.close.call_count == 2


async def test_create_session_with_script_config_overrides(
    session_manager: SessionManager,
    mock_session_consumer: SessionConsumer,
    tmp_path: Path,
) -> None:
    tmp_file = tmp_path / "test.py"
    tmp_file.write_text(
        dedent(
            """
        # /// script
        # [tool.marimo.formatting]
        # line_length = 999
        # ///
        """
        )
    )

    session = await session_manager.create_session(
        session_id,
        mock_session_consumer,
        query_params={},
        file_key=str(tmp_path / "test.py"),
        auto_instantiate=False,
        main=True,
    )
    assert session_id in session_manager.sessions
    assert session_manager.get_session(session_id) is session

    # Verify that the session's config is affected by the script config
    assert (
        session.config_manager.get_config()["formatting"]["line_length"] == 999
    )

    # Verify that the session manager's config is not affected by the script config
    assert (
        session_manager._config_manager.get_config()["formatting"][
            "line_length"
        ]
        != 999
    )

    session.close()


def test_session_manager_auth_token_edit_mode_with_provided_token():
    """Test that provided auth token is used in EDIT mode"""
    provided_token = AuthToken("custom-edit-token")
    session_manager = SessionManager(
        workspace=EmptyWorkspace(),
        mode=SessionMode.EDIT,
        quiet=False,
        include_code=True,
        lsp_server=MagicMock(spec=LspServer),
        config_manager=get_default_config_manager(current_path=None),
        cli_args={},
        argv=None,
        auth_token=provided_token,
        redirect_console_to_browser=False,
        ttl_seconds=None,
    )

    assert session_manager.auth_token is provided_token
    assert str(session_manager.auth_token) == "custom-edit-token"
    assert session_manager.skew_protection_token is not None


def test_session_manager_auth_token_edit_mode_without_provided_token():
    """Test that random auth token is generated in EDIT mode when none provided"""
    session_manager = SessionManager(
        workspace=EmptyWorkspace(),
        mode=SessionMode.EDIT,
        quiet=False,
        include_code=True,
        lsp_server=MagicMock(spec=LspServer),
        config_manager=get_default_config_manager(current_path=None),
        cli_args={},
        argv=None,
        auth_token=None,
        redirect_console_to_browser=False,
        ttl_seconds=None,
    )

    # Should generate a random token (we can't predict the value, but it should exist)
    assert session_manager.auth_token is not None
    assert str(session_manager.auth_token) != ""
    # Verify it's a random token by checking length (AuthToken.random() uses token_urlsafe(16))
    assert len(str(session_manager.auth_token)) > 10
    assert session_manager.skew_protection_token is not None


def test_session_manager_auth_token_run_mode_with_provided_token():
    """Test that provided auth token is used in RUN mode"""
    provided_token = AuthToken("custom-run-token")
    session_manager = SessionManager(
        workspace=EmptyWorkspace(),
        mode=SessionMode.RUN,
        quiet=False,
        include_code=True,
        lsp_server=MagicMock(spec=LspServer),
        config_manager=get_default_config_manager(current_path=None),
        cli_args={},
        argv=None,
        auth_token=provided_token,
        redirect_console_to_browser=False,
        ttl_seconds=None,
    )

    assert session_manager.auth_token is provided_token
    assert str(session_manager.auth_token) == "custom-run-token"
    assert str(session_manager.skew_protection_token) == str(
        SkewProtectionToken.from_code("")
    )


def test_session_manager_auth_token_run_mode_without_provided_token(
    tmp_path: Path,
):
    """Test that code-based auth token is generated in RUN mode when none provided"""
    # Create a simple marimo file
    notebook_content = dedent(
        """\
        import marimo

        app = marimo.App()

        @app.cell
        def test_cell():
            "hello"
            return
        """
    )

    file_path = tmp_path / "test_notebook.py"
    file_path.write_text(notebook_content)

    session_manager = SessionManager(
        workspace=infer_workspace(str(file_path)),
        mode=SessionMode.RUN,
        quiet=False,
        include_code=True,
        lsp_server=MagicMock(spec=LspServer),
        config_manager=get_default_config_manager(current_path=None),
        cli_args={},
        argv=None,
        auth_token=None,
        redirect_console_to_browser=False,
        ttl_seconds=None,
    )

    # Should generate a deterministic token based on code
    assert session_manager.auth_token is not None
    assert str(session_manager.auth_token) != ""
    assert str(session_manager.skew_protection_token) != ""

    # Create another session manager with the same code - should have same token
    session_manager2 = SessionManager(
        workspace=infer_workspace(str(file_path)),
        mode=SessionMode.RUN,
        quiet=False,
        include_code=True,
        lsp_server=MagicMock(spec=LspServer),
        config_manager=get_default_config_manager(current_path=None),
        cli_args={},
        argv=None,
        auth_token=None,
        redirect_console_to_browser=False,
        ttl_seconds=None,
    )

    # Should have the same deterministic token
    assert str(session_manager.auth_token) == str(session_manager2.auth_token)
    assert str(session_manager.skew_protection_token) == str(
        session_manager2.skew_protection_token
    )


def test_recents_listener_subscribed_to_event_bus(
    session_manager: SessionManager,
) -> None:
    """Test that RecentsTrackerListener is subscribed to session manager's event bus.

    This is a regression test for a bug where the listener was moved to be a
    session extension (subscribing to the session's event bus) but the
    emit_session_created event was still fired on the session manager's event bus,
    causing recent files to not be tracked.
    """
    # Verify that RecentsTrackerListener is in the event bus listeners
    listeners = session_manager._event_bus._listeners
    recents_listeners = [
        listen
        for listen in listeners
        if isinstance(listen, RecentsTrackerListener)
    ]
    assert len(recents_listeners) == 1, (
        "RecentsTrackerListener should be subscribed to session manager's event bus"
    )


async def test_recents_touch_called_on_session_create(
    session_manager: SessionManager,
    mock_session_consumer: SessionConsumer,
    tmp_path: Path,
) -> None:
    """Test that recents.touch() is called when a session is created with a file.

    This verifies the full integration: when a session is created for a file,
    the RecentsTrackerListener receives the event and calls touch().
    """
    # Create a temp marimo file
    tmp_file = tmp_path / "test_recents.py"
    tmp_file.write_text(
        "import marimo\napp = marimo.App()\n@app.cell\ndef _(): pass"
    )

    # Track calls to touch()
    original_touch = session_manager.recents.touch
    touched_files: list[str] = []

    def mock_touch(filename: str) -> None:
        touched_files.append(filename)
        original_touch(filename)

    session_manager.recents.touch = mock_touch  # type: ignore

    # Create a session
    session = await session_manager.create_session(
        SessionId("recents_test_session"),
        mock_session_consumer,
        query_params={},
        file_key=str(tmp_file),
        auto_instantiate=False,
        main=True,
    )

    # Allow async event to process
    import asyncio

    await asyncio.sleep(0.1)

    # Verify touch was called with the file path
    assert len(touched_files) == 1
    assert str(tmp_file) in touched_files[0]

    session.close()


async def test_concurrent_startup_survives_disconnected_waiter(
    session_manager: SessionManager,
    mock_session: Session,
    mock_session_consumer: SessionConsumer,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from marimo._session.session import SessionImpl

    entered = asyncio.Event()
    release = asyncio.Event()
    launches = 0
    mock_session.app_file_manager = AppFileManager(filename=None)

    async def create(**_kwargs: object) -> Session:
        nonlocal launches
        launches += 1
        entered.set()
        await release.wait()
        return mock_session

    monkeypatch.setattr(SessionImpl, "create", create)

    async def connect() -> Session:
        return await session_manager.create_session(
            session_id, mock_session_consumer, {}, NEW_FILE, False, main=True
        )

    first = asyncio.create_task(connect())
    try:
        await asyncio.wait_for(entered.wait(), 5)
        assert not session_manager.sessions
        second_entered = asyncio.Event()

        async def reconnect() -> Session:
            second_entered.set()
            return await connect()

        second = asyncio.create_task(reconnect())
        await asyncio.wait_for(second_entered.wait(), 5)
        first.cancel()
        with pytest.raises(asyncio.CancelledError):
            await first
        release.set()
        assert await asyncio.wait_for(second, 5) is mock_session
        assert launches == 1
    finally:
        await session_manager.shutdown()


async def test_shutdown_waits_for_pending_startup_cleanup(
    session_manager: SessionManager,
    mock_session_consumer: SessionConsumer,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from marimo._session.managers.ipc import KernelStartupError
    from marimo._session.session import SessionImpl

    entered = asyncio.Event()
    cleaning_up = asyncio.Event()
    release = asyncio.Event()

    async def create(**_kwargs: object) -> Session:
        entered.set()
        try:
            await asyncio.Event().wait()
        finally:
            cleaning_up.set()
            await release.wait()
        raise AssertionError("unreachable")

    monkeypatch.setattr(SessionImpl, "create", create)
    startup = asyncio.create_task(
        session_manager.create_session(
            session_id, mock_session_consumer, {}, NEW_FILE, False, main=True
        )
    )
    await asyncio.wait_for(entered.wait(), 5)
    shutdown = asyncio.create_task(session_manager.shutdown())
    try:
        await asyncio.wait_for(cleaning_up.wait(), 5)
        assert not shutdown.done()
        assert not session_manager.sessions
        with pytest.raises(KernelStartupError, match="shut down"):
            await session_manager.create_session(
                session_id,
                mock_session_consumer,
                {},
                NEW_FILE,
                False,
                main=True,
            )
    finally:
        release.set()
        await asyncio.wait_for(shutdown, 5)
        with pytest.raises(asyncio.CancelledError):
            await startup
    assert not session_manager.sessions


async def test_connections_share_starting_notebook(
    session_manager: SessionManager,
    mock_session: Session,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from starlette.requests import HTTPConnection

    from marimo._server.api.endpoints.ws.ws_connection_validator import (
        ConnectionParams,
    )
    from marimo._server.api.endpoints.ws.ws_session_connector import (
        SessionConnector,
    )
    from marimo._session.session import SessionImpl

    entered = asyncio.Event()
    release = asyncio.Event()
    mock_session.initialization_id = NEW_FILE
    mock_session.room = MagicMock()
    mock_session.room.main_consumer = None
    mock_session.room.get_consumer.return_value = None
    mock_session.app_file_manager = AppFileManager(filename=None)
    launches = 0

    async def create(**_kwargs: object) -> Session:
        nonlocal launches
        launches += 1
        entered.set()
        await release.wait()
        return mock_session

    monkeypatch.setattr(SessionImpl, "create", create)

    def connector(sid: str) -> SessionConnector:
        return SessionConnector(
            manager=session_manager,
            handler=MagicMock(_prepare_session=AsyncMock()),
            params=ConnectionParams(
                session_id=SessionId(sid),
                file_key=NEW_FILE,
                kiosk=False,
                auto_instantiate=False,
            ),
            connection=HTTPConnection({"type": "http", "query_string": b""}),
        )

    first_connector = connector("first")
    second_connector = connector("second")
    first = asyncio.create_task(first_connector.connect())
    try:
        await asyncio.wait_for(entered.wait(), 5)
        second = asyncio.create_task(second_connector.connect())
        # Scheduling the second connection before releasing preparation
        # exercises its decision against an initially empty repository.
        release.set()
        await asyncio.wait_for(first, 5)
        await asyncio.wait_for(second, 5)
        mock_session.connect_consumer.assert_called_once_with(
            first_connector.handler, main=True
        )
        first_connector.handler._write_kernel_ready.assert_called_once()
        second_connector.handler._connect_kiosk.assert_called_once_with(
            mock_session
        )
        assert launches == 1
    finally:
        release.set()
        await session_manager.shutdown()


@pytest.mark.parametrize("replacement_id", ["first", "refreshed"])
@pytest.mark.parametrize("finish_disconnected", [False, True])
async def test_refresh_reuses_pending_startup(
    session_manager: SessionManager,
    mock_session: Session,
    monkeypatch: pytest.MonkeyPatch,
    replacement_id: str,
    finish_disconnected: bool,
) -> None:
    from starlette.requests import HTTPConnection

    from marimo._messaging.notification import (
        EnvironmentState,
        EnvironmentStateNotification,
        StartupProgressNotification,
    )
    from marimo._messaging.serde import deserialize_kernel_message
    from marimo._server.api.endpoints.ws.ws_connection_validator import (
        ConnectionParams,
    )
    from marimo._server.api.endpoints.ws.ws_session_connector import (
        SessionConnector,
    )
    from marimo._session.session import SessionImpl
    from marimo._session.startup import SessionStartup

    entered, release, finished, restored = (asyncio.Event() for _ in range(4))
    progress = StartupProgressNotification(
        phase="preparing-environment", logs="", log_mode="replace"
    )
    starting = StartupProgressNotification(
        phase="starting-kernel", logs="Launching kernel\n", log_mode="replace"
    )
    launches = 0
    mock_session.initialization_id = NEW_FILE
    mock_session.app_file_manager = AppFileManager(filename=None)

    async def create(*, startup: SessionStartup, **_kwargs: object) -> Session:
        nonlocal launches
        launches += 1
        mock_session.session_view = startup.view
        startup.notify(progress)
        entered.set()
        await release.wait()
        startup.notify(starting)
        startup.notify(
            StartupProgressNotification(
                phase="starting-kernel",
                logs="Loading runtime\n",
                log_mode="append",
            )
        )
        finished.set()
        return mock_session

    monkeypatch.setattr(SessionImpl, "create", create)

    def connector(sid: str) -> SessionConnector:
        handler = MagicMock(consumer_id=sid, _prepare_session=AsyncMock())
        return SessionConnector(
            manager=session_manager,
            handler=handler,
            params=ConnectionParams(
                session_id=SessionId(sid),
                file_key=NEW_FILE,
                kiosk=False,
                auto_instantiate=False,
            ),
            connection=HTTPConnection({"type": "http", "query_string": b""}),
        )

    first = connector("first")
    first_connection = asyncio.create_task(first.connect())
    try:
        await asyncio.wait_for(entered.wait(), 5)
        first_connection.cancel()
        with pytest.raises(asyncio.CancelledError):
            await first_connection
        assert session_manager.is_session_starting(
            SessionId(replacement_id), NEW_FILE
        )
        if finish_disconnected:
            release.set()
            await asyncio.wait_for(finished.wait(), 5)

        refreshed = connector(replacement_id)
        refreshed.handler.notify.side_effect = lambda _message: restored.set()
        next_connection = asyncio.create_task(refreshed.connect())
        await asyncio.wait_for(restored.wait(), 5)
        assert [
            deserialize_kernel_message(call.args[0])
            for call in refreshed.handler.notify.call_args_list
        ] == [
            StartupProgressNotification(
                phase="starting-kernel",
                logs="Launching kernel\nLoading runtime\n",
                log_mode="replace",
            )
            if finish_disconnected
            else progress,
            *[
                EnvironmentStateNotification(
                    source=source,
                    state=EnvironmentState(
                        restart_required=False, operations=[]
                    ),
                )
                for source in ("kernel", "server")
            ],
        ]
        release.set()
        await asyncio.wait_for(next_connection, 5)
        assert launches == 1
        assert (
            session_manager.get_session(SessionId(replacement_id))
            is mock_session
        )
        assert mock_session.room.main_consumer is refreshed.handler
        assert (
            mock_session.session_view.startup_progress
            == StartupProgressNotification(
                phase="starting-kernel",
                logs="Launching kernel\nLoading runtime\n",
                log_mode="replace",
            )
        )
        assert not session_manager.is_session_starting(
            SessionId(replacement_id), NEW_FILE
        )
        refreshed.handler._write_kernel_ready.assert_called_once()
        assert (
            refreshed.handler._write_kernel_ready.call_args.kwargs["resumed"]
            is False
        )
    finally:
        release.set()
        await session_manager.shutdown()


async def test_abandoned_completed_startup_expires(
    session_manager: SessionManager,
    mock_session: Session,
    mock_session_consumer: SessionConsumer,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from marimo._session.session import SessionImpl

    entered, release, closed = (asyncio.Event() for _ in range(3))
    session_manager.ttl_seconds = 0
    mock_session.app_file_manager = AppFileManager(filename=None)
    mock_session.close.side_effect = lambda: closed.set()

    async def create(**_kwargs: object) -> Session:
        entered.set()
        await release.wait()
        return mock_session

    monkeypatch.setattr(SessionImpl, "create", create)
    connection = asyncio.create_task(
        session_manager.create_session(
            session_id,
            mock_session_consumer,
            {},
            NEW_FILE,
            False,
            main=True,
        )
    )
    try:
        await asyncio.wait_for(entered.wait(), 5)
        # Completion is queued before expiry, but the browser never attaches.
        release.set()
        connection.cancel()
        with pytest.raises(asyncio.CancelledError):
            await connection
        await asyncio.wait_for(closed.wait(), 5)
        assert not session_manager.sessions
        assert not session_manager.is_session_starting(session_id, NEW_FILE)
    finally:
        await session_manager.shutdown()


async def test_startup_retention_ignores_long_session_ttl(
    session_manager: SessionManager,
    mock_session: Session,
    mock_session_consumer: SessionConsumer,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from marimo._server.session_manager import _STARTUP_RECONNECT_SECONDS
    from marimo._session.session import SessionImpl

    entered = asyncio.Event()
    session_manager.ttl_seconds = 3600
    mock_session.app_file_manager = AppFileManager(filename=None)

    async def create(**_kwargs: object) -> Session:
        entered.set()
        await asyncio.Event().wait()
        return mock_session

    monkeypatch.setattr(SessionImpl, "create", create)
    connection = asyncio.create_task(
        session_manager.create_session(
            session_id,
            mock_session_consumer,
            {},
            NEW_FILE,
            False,
            main=True,
        )
    )
    try:
        await asyncio.wait_for(entered.wait(), 5)
        connection.cancel()
        with pytest.raises(asyncio.CancelledError):
            await connection
        key = session_manager._connection_key(session_id, NEW_FILE)
        handle = session_manager._pending[key].close_handle
        assert handle is not None
        remaining = handle.when() - asyncio.get_running_loop().time()
        assert 0 < remaining <= _STARTUP_RECONNECT_SECONDS
    finally:
        await session_manager.shutdown()


async def test_startup_never_hands_out_a_session_owned_by_another_consumer(
    session_manager: SessionManager,
    mock_session: Session,
    mock_session_consumer: SessionConsumer,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from marimo._session.session import SessionImpl

    mock_session.app_file_manager = AppFileManager(filename=None)
    other = Mock(spec=SessionConsumer)
    other.consumer_id = "other_consumer_id"
    mock_session.room.add_consumer(other, main=True)

    async def create(**_kwargs: object) -> Session:
        return mock_session

    monkeypatch.setattr(SessionImpl, "create", create)
    try:
        with pytest.raises(RuntimeError, match="main consumer"):
            await session_manager.create_session(
                session_id,
                mock_session_consumer,
                {},
                NEW_FILE,
                False,
                main=True,
            )
        assert mock_session.room.main_consumer is other
        assert not session_manager.is_session_starting(session_id, NEW_FILE)
    finally:
        await session_manager.shutdown()


async def test_secondary_consumer_joins_beside_the_main_one(
    session_manager: SessionManager,
    mock_session: Session,
    mock_session_consumer: SessionConsumer,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from marimo._session.session import SessionImpl

    mock_session.app_file_manager = AppFileManager(filename=None)
    other = Mock(spec=SessionConsumer)
    other.consumer_id = "other_consumer_id"
    mock_session.room.add_consumer(other, main=True)

    async def create(**_kwargs: object) -> Session:
        return mock_session

    monkeypatch.setattr(SessionImpl, "create", create)
    try:
        session = await session_manager.create_session(
            session_id,
            mock_session_consumer,
            {},
            NEW_FILE,
            False,
            main=False,
        )
        assert session is mock_session
        assert mock_session.room.main_consumer is other
        assert mock_session.room.size == 2
        assert not session_manager.is_session_starting(session_id, NEW_FILE)
    finally:
        await session_manager.shutdown()


async def test_secondary_consumer_leaves_the_main_seat_open(
    session_manager: SessionManager,
    mock_session: Session,
    mock_session_consumer: SessionConsumer,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from marimo._session.session import SessionImpl

    mock_session.app_file_manager = AppFileManager(filename=None)

    async def create(**_kwargs: object) -> Session:
        return mock_session

    monkeypatch.setattr(SessionImpl, "create", create)
    try:
        await session_manager.create_session(
            session_id,
            mock_session_consumer,
            {},
            NEW_FILE,
            False,
            main=False,
        )
        assert mock_session.room.main_consumer is None
        assert mock_session.room.size == 1
        # A secondary consumer completes startup, preventing expiration.
        assert not session_manager.is_session_starting(session_id, NEW_FILE)
    finally:
        await session_manager.shutdown()


async def test_retry_waits_for_expired_startup_cleanup(
    session_manager: SessionManager,
    mock_session: Session,
    mock_session_consumer: SessionConsumer,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from marimo._session.session import SessionImpl

    entered, cleaning_up, release_cleanup = (asyncio.Event() for _ in range(3))
    session_manager.ttl_seconds = 0
    mock_session.app_file_manager = AppFileManager(filename=None)
    launches = 0

    async def create(**_kwargs: object) -> Session:
        nonlocal launches
        launches += 1
        if launches == 1:
            entered.set()
            try:
                await asyncio.Event().wait()
            finally:
                cleaning_up.set()
                await release_cleanup.wait()
        return mock_session

    monkeypatch.setattr(SessionImpl, "create", create)
    first = asyncio.create_task(
        session_manager.create_session(
            session_id,
            mock_session_consumer,
            {},
            NEW_FILE,
            False,
            main=True,
        )
    )
    try:
        await asyncio.wait_for(entered.wait(), 5)
        first.cancel()
        with pytest.raises(asyncio.CancelledError):
            await first
        await asyncio.wait_for(cleaning_up.wait(), 5)
        retry = asyncio.create_task(
            session_manager.create_session(
                SessionId("refreshed"),
                mock_session_consumer,
                {},
                NEW_FILE,
                False,
                main=True,
            )
        )
        await asyncio.sleep(0)
        assert launches == 1
        release_cleanup.set()
        assert await asyncio.wait_for(retry, 5) is mock_session
        assert launches == 2
    finally:
        release_cleanup.set()
        await session_manager.shutdown()


@pytest.mark.parametrize("close_before_attachment", [False, True])
async def test_closed_startup_cannot_be_attached(
    session_manager: SessionManager,
    mock_session: Session,
    mock_session_consumer: SessionConsumer,
    monkeypatch: pytest.MonkeyPatch,
    close_before_attachment: bool,
) -> None:
    from marimo._session.managers.ipc import KernelStartupError
    from marimo._session.session import SessionImpl

    entered, release = asyncio.Event(), asyncio.Event()
    mock_session.app_file_manager = AppFileManager(filename=None)

    async def create(**_kwargs: object) -> Session:
        entered.set()
        await release.wait()
        return mock_session

    monkeypatch.setattr(SessionImpl, "create", create)
    first = asyncio.create_task(
        session_manager.create_session(
            session_id, mock_session_consumer, {}, NEW_FILE, False, main=True
        )
    )
    try:
        await asyncio.wait_for(entered.wait(), 5)
        pending = next(iter(session_manager._pending.values()))
        if close_before_attachment:
            # The task publishes its session before the waiter can attach.
            pending.task.add_done_callback(
                lambda _: session_manager.close_session(session_id)
            )
            release.set()
            with pytest.raises(
                KernelStartupError, match="closed during startup"
            ):
                await asyncio.wait_for(first, 5)
        else:
            first.cancel()
            with pytest.raises(asyncio.CancelledError):
                await first
            release.set()
            await asyncio.wait_for(asyncio.shield(pending.task), 5)
            assert session_manager.close_session(session_id)

        mock_session.connect_consumer.assert_not_called()
        assert not session_manager.is_session_starting(session_id, NEW_FILE)
        assert not session_manager.sessions

        replacement = Mock(spec=Session)
        replacement.room = Room()
        replacement.connect_consumer.side_effect = (
            replacement.room.add_consumer
        )
        replacement.connection_state.return_value = ConnectionState.ORPHANED
        replacement.app_file_manager = mock_session.app_file_manager

        async def restart(**_kwargs: object) -> Session:
            return replacement

        monkeypatch.setattr(SessionImpl, "create", restart)
        assert (
            await session_manager.create_session(
                session_id,
                mock_session_consumer,
                {},
                NEW_FILE,
                False,
                main=True,
            )
            is replacement
        )
        assert session_manager.get_session(session_id) is replacement
        assert replacement.room.main_consumer is mock_session_consumer
    finally:
        release.set()
        await session_manager.shutdown()