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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Harden sandbox environment selection (#11026)
Trevor Manz7334dc17c3da
diff --git a/docs/guides/editor_features/home.md b/docs/guides/editor_features/home.mdindex 1b77b7bd8c..bf3190a125 100644--- a/docs/guides/editor_features/home.md+++ b/docs/guides/editor_features/home.md@@ -40,10 +40,10 @@ Each environment is prepared from the notebook's requirements when you open it.See [working in sandboxes](../package_management/sandboxes.md#open-a-directory-of-notebooks)for setup with uv or Pixi.-### Using custom virtual environments+## Using custom virtual environments-When using Sandboxed Home, you can specify an existing virtual environment-for a notebook instead of having marimo create one automatically.+You can specify an existing virtual environment for each notebook when editing+a directory or a single notebook with `marimo edit --no-sandbox`.This is configured using `[tool.marimo.venv]` in your script metadata:```python@@ -54,20 +54,20 @@ This is configured using `[tool.marimo.venv]` in your script metadata:# ///```-This configuration also applies when editing a single file with-`marimo edit --sandbox notebook.py`. The configured environment takes precedence-over creating an environment from inline requirements. To use an activated+With `--sandbox`, uv or Pixi provisions the environment from the notebook's+manifest. The editor ignores `[tool.marimo.venv]` and prints a warning.+Use `--no-sandbox` to use the configured environment. To use an activatedenvironment directly, see[using an existing environment](../package_management/projects.md#use-an-existing-environment).-#### Configuration options+### Configuration options| Option | Description ||--------|-------------|| `path` | Path to the virtual environment (relative or absolute) || `writable` | Whether marimo can install packages into the venv (default: `false`) |-#### Behavior+### Behavior| `writable` | marimo installed? | What happens ||:-----------|:------------------|:-------------|diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex 0762192a94..725cb2ce21 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -101,10 +101,10 @@ ExecutionType = Literal["relaxed", "strict"]@mddoc@dataclassclass VenvConfig(TypedDict, total=False):- """Configuration for external Python environment in home sandbox mode.+ """Configuration for an external Python environment in edit mode.- Allows specifying an existing virtualenv to use instead of creating- ephemeral sandboxes per notebook. Only applies in home sandbox mode.+ Launches the notebook kernel in an existing virtualenv. Applies to+ single notebooks and directories when editing without `--sandbox`.**Keys.**diff --git a/marimo/_session/_venv.py b/marimo/_session/_venv.pyindex 4b05b21b1b..ff1a9e694e 100644--- a/marimo/_session/_venv.py+++ b/marimo/_session/_venv.py@@ -1,8 +1,8 @@# Copyright 2026 Marimo. All rights reserved."""Virtual environment configuration utilities.-This module provides utilities for working with configured virtual environments-in marimo's sandbox mode. It handles:+This module provides utilities for launching editor kernels in configured+virtual environments. It handles:- Finding Python interpreters in virtual environments- Checking marimo installation status in venvs- PYTHONPATH injection for kernel subprocessesdiff --git a/marimo/_session/managers/__init__.py b/marimo/_session/managers/__init__.pyindex 71ab6ce2c0..3a3d6b8134 100644--- a/marimo/_session/managers/__init__.py+++ b/marimo/_session/managers/__init__.py@@ -10,7 +10,6 @@ Standard implementations (QueueManagerImpl, KernelManagerImpl):IPC implementations (IPCQueueManagerImpl, IPCKernelManagerImpl):Launch kernel as subprocess with ZeroMQ IPC.- Each notebook gets its own sandboxed virtual environment."""from marimo._session.managers.ipc import (diff --git a/marimo/_session/managers/ipc.py b/marimo/_session/managers/ipc.pyindex 015cf2f5ea..83e1a3998c 100644--- a/marimo/_session/managers/ipc.py+++ b/marimo/_session/managers/ipc.py@@ -2,7 +2,7 @@"""IPC-based managers using ZeroMQ.These implementations launch the kernel as a subprocess and communicate-via ZeroMQ channels. Each notebook gets its own sandboxed virtual environment.+via ZeroMQ channels."""from __future__ import annotations@@ -236,9 +236,7 @@ def construct_kernel_env("""env = dict(base_env)- # Sandbox identity is per-kernel, not inherited: a configured venv- # kernel inside a sandboxed server must not route package changes- # through a script environment it does not run in.+ # Sandbox identity is per-kernel, not inherited.env.pop("MARIMO_SANDBOX_MODE", None)env.pop("MARIMO_SANDBOX_BACKEND", None)env.pop("MARIMO_MANAGE_SCRIPT_METADATA", None)@@ -266,15 +264,12 @@ def construct_kernel_env(class IPCKernelManagerImpl(KernelManager):- """IPC-based kernel manager to spawn sandboxed kernels.-- Launches the kernel as a subprocess and communicates via ZeroMQ channels.- Each notebook gets its own sandboxed virtual environment.- """+ """Launches a kernel subprocess and communicates via ZeroMQ channels."""def __init__(self,*,+ sandbox: bool,queue_manager: IPCQueueManagerImpl,connection_info: ConnectionInfo,mode: SessionMode,@@ -284,6 +279,7 @@ class IPCKernelManagerImpl(KernelManager):redirect_console_to_browser: bool = True,on_notification: Callable[[NotificationMessage], None] | None = None,) -> None:+ self._sandbox = sandboxself.queue_manager = queue_managerself.connection_info = connection_infoself.mode = mode@@ -334,20 +330,26 @@ class IPCKernelManagerImpl(KernelManager):"prepare", {}, "kernel", self._notify) as operation:venv_config = _get_venv_config(self.config_manager)+ if self._sandbox and venv_config.get("path"):+ echo(+ "Warning: ignoring [tool.marimo.venv] in sandbox mode. "+ "Use --no-sandbox to edit with the configured environment.",+ err=True,+ )try:- configured_python = get_configured_venv_python(- venv_config, base_path=self.app_metadata.filename+ configured_python = (+ None+ if self._sandbox+ else get_configured_venv_python(+ venv_config, base_path=self.app_metadata.filename+ ))except ValueError as e:raise KernelStartupError(str(e)) from e- # Ephemeral sandboxes are always writable; configured venvs respect the- # flag.writable = Truekernel_pythonpath: str | None = None- # An explicitly configured venv takes precedence over an ephemeral- # sandbox.if configured_python:echo(f"Using configured venv: {muted(configured_python)}",@@ -389,7 +391,7 @@ class IPCKernelManagerImpl(KernelManager):f"Options:\n"f" 1. Set writable=true in [tool.marimo.venv] to allow marimo to install deps\n"f" 2. Install marimo in your venv: uv pip install marimo --python {venv_python}\n"- f" 3. Remove [tool.marimo.venv].path to use an ephemeral sandbox instead"+ f" 3. Launch with --sandbox to use the notebook's requirements")# Inject PYTHONPATH for marimo and dependencies from thediff --git a/marimo/_session/session.py b/marimo/_session/session.pyindex 9294c72092..7727b6fbef 100644--- a/marimo/_session/session.py+++ b/marimo/_session/session.py@@ -124,12 +124,13 @@ class SessionImpl(Session):config_manager = config_manager.with_partial(ScriptConfigManager(app_file_manager.path))+ config = config_manager.get_config(hide_secrets=False)+ configured_venv = config.get("venv", {}).get("path")configs = app_file_manager.app.cell_manager.config_map()# Create kernel manager# AppHost path handles multi-app run mode (both sandbox and non-sandbox).- # Sandboxed edit sessions use IPC kernels.queue_manager: QueueManagerkernel_manager: KernelManagerif app_host_context is not None and mode == SessionMode.RUN:@@ -157,8 +158,7 @@ class SessionImpl(Session):config_manager=config_manager,redirect_console_to_browser=redirect_console_to_browser,)- elif sandbox:- # IPC kernel path — edit mode with sandbox+ elif sandbox or (mode == SessionMode.EDIT and configured_venv):# (AppHostPool is never created in edit mode)from marimo._ipc import QueueManager as IPCQueueManagerfrom marimo._session.managers import (@@ -169,6 +169,7 @@ class SessionImpl(Session):ipc_queue_manager, connection_info = IPCQueueManager.create()queue_manager = IPCQueueManagerImpl.from_ipc(ipc_queue_manager)kernel_manager = IPCKernelManagerImpl(+ sandbox=sandbox,queue_manager=queue_manager,connection_info=connection_info,mode=mode,diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex e8de89183e..754877bbda 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -6577,12 +6577,12 @@ components:title: VariablesNotificationtype: objectVenvConfig:- description: "Configuration for external Python environment in home sandbox\- \ mode.\n\n Allows specifying an existing virtualenv to use instead of\- \ creating\n ephemeral sandboxes per notebook. Only applies in home sandbox\- \ mode.\n\n **Keys.**\n\n - `path`: path to a virtualenv directory (absolute\- \ or relative to\n pyproject.toml)\n - `writable`: if true, marimo\- \ will manage script metadata (inline\n dependencies). Defaults to false."+ description: "Configuration for an external Python environment in edit mode.\n\n\+ \ Launches the notebook kernel in an existing virtualenv. Applies to\n single\+ \ notebooks and directories when editing without `--sandbox`.\n\n **Keys.**\n\+ \n - `path`: path to a virtualenv directory (absolute or relative to\n \+ \ pyproject.toml)\n - `writable`: if true, marimo will manage script metadata\+ \ (inline\n dependencies). Defaults to false."properties:path:type: stringdiff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex 16114ab42a..a6aeb0d17a 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -7851,10 +7851,10 @@ export interface components {};/*** VenvConfig- * @description Configuration for external Python environment in home sandbox mode.+ * @description Configuration for an external Python environment in edit mode.*- * Allows specifying an existing virtualenv to use instead of creating- * ephemeral sandboxes per notebook. Only applies in home sandbox mode.+ * Launches the notebook kernel in an existing virtualenv. Applies to+ * single notebooks and directories when editing without `--sandbox`.** **Keys.***diff --git a/tests/_server/api/endpoints/test_sse.py b/tests/_server/api/endpoints/test_sse.pyindex 5f5cfc2015..7bef2f8de8 100644--- a/tests/_server/api/endpoints/test_sse.py+++ b/tests/_server/api/endpoints/test_sse.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport asyncioimport json+import osimport sysimport threadingfrom functools import partial@@ -11,6 +12,9 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest+from marimo._environments import backends+from marimo._environments.environment import Environment, ProcessPlan+from marimo._environments.sandbox import BackendAdapterfrom marimo._messaging.notification import (AlertNotification,StartupProgressNotification,@@ -303,30 +307,33 @@ async def test_sandbox_progress_during_preparation(tmp_path: Path,outcome: str,) -> None:- from marimo._session.managers import ipc-+ preparing = asyncio.Event()release = asyncio.Event()cleaned_up = asyncio.Event()+ python = (+ sys.executable+ if outcome == "ready"+ else str(tmp_path / "missing-python")+ )+ environment = Environment(python, sys.prefix, "unchanged")- async def check_environment(_python: str) -> bool:+ async def prepare_environment(*_args: Any, **_kwargs: Any) -> Environment:+ preparing.set()try:await release.wait()- return True+ return environmentfinally:cleaned_up.set()- # A configured interpreter that disappears before launch lets the test- # observe both phases and a real launch failure without spawning a kernel.- monkeypatch.setattr(- ipc,- "get_configured_venv_python",- lambda *_args, **_kwargs: (- sys.executable- if outcome == "ready"- else str(tmp_path / "missing-python")- ),+ # Control sandbox preparation while exercising real kernel startup.+ # A missing interpreter triggers a launch failure after preparation succeeds.+ adapter = MagicMock(spec=BackendAdapter)+ adapter.name = backends.current_backend()+ adapter.sync_async.side_effect = prepare_environment+ adapter.launch.return_value = ProcessPlan(+ (python, "-m", "marimo._ipc.launch_kernel"), os.environ.copy())- monkeypatch.setattr(ipc, "has_marimo_installed", check_environment)+ monkeypatch.setattr(backends, "adapter_for", lambda *_: adapter)manager = get_session_manager(client)manager.sandbox = Trueif outcome == "disconnect":@@ -348,6 +355,7 @@ async def test_sandbox_progress_during_preparation(assert running["data"]["action"] == "prepare"assert running["data"]["status"] == {"kind": "running"}assert not manager.sessions+ await asyncio.wait_for(preparing.wait(), timeout=5)if outcome == "disconnect":connection.disconnect()await asyncio.wait_for(cleaned_up.wait(), timeout=5)diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.pyindex 3ba13775e6..43809178af 100644--- a/tests/_server/test_sessions.py+++ b/tests/_server/test_sessions.py@@ -1168,6 +1168,123 @@ async def test_session_with_script_config_overrides(session.close()[email protected]("zmq")[email protected]("backend", ["uv", "pixi"])[email protected]("config_source", ["script", "project"])[email protected]("existing_venv", [False, True])+async def test_sandbox_ignores_configured_venv(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+ backend: str,+ config_source: str,+ existing_venv: bool,+) -> None:+ from marimo._config.settings import GLOBAL_SETTINGS+ from marimo._environments.environment import Environment, ProcessPlan+ from marimo._environments.sandbox import BackendAdapter, NotebookSandbox++ venv_path = Path(sys.prefix) if existing_venv else tmp_path / "missing"+ config = (+ f"[tool.marimo.venv]\npath = {venv_path.as_posix()!r}\n"+ "writable = false\n"+ )+ if config_source == "project":+ (tmp_path / "pyproject.toml").write_text(config)+ header = "# /// script\n# dependencies = []\n"+ if config_source == "script":+ header += "".join(f"# {line}\n" for line in config.splitlines())+ notebook = tmp_path / "notebook.py"+ notebook.write_text(header + "# ///\n")+ monkeypatch.setattr(GLOBAL_SETTINGS, "SANDBOX_BACKEND", backend)++ environment = Environment(sys.executable, sys.prefix, "unchanged")+ adapter = MagicMock(spec=BackendAdapter)+ adapter.name = backend+ adapter.sync_async.return_value = environment+ adapter.launch.return_value = ProcessPlan(+ (sys.executable, "-m", "marimo._ipc.launch_kernel"), os.environ.copy()+ )+ monkeypatch.setattr(+ "marimo._environments.backends.adapter_for", lambda *_: adapter+ )++ session = await SessionImpl.create(+ initialization_id=str(notebook),+ startup=SessionStartup(),+ session_consumer=None,+ mode=SessionMode.EDIT,+ app_metadata=AppMetadata(+ query_params={},+ filename=str(notebook),+ cli_args={},+ app_config=_AppConfig(),+ ),+ app_file_manager=AppFileManager(filename=str(notebook)),+ config_manager=get_default_config_manager(current_path=str(tmp_path)),+ virtual_file_storage=None,+ redirect_console_to_browser=False,+ ttl_seconds=None,+ auto_instantiate=False,+ sandbox=True,+ )+ try:+ assert session._kernel_manager.is_alive()+ sandbox = session.notebook_sandbox+ assert isinstance(sandbox, NotebookSandbox)+ assert sandbox.backend == backend+ assert sandbox.environment == environment+ adapter.sync_async.assert_awaited_once()+ assert "ignoring [tool.marimo.venv]" in capsys.readouterr().err+ assert (+ session.config_manager.get_config()["venv"]["path"]+ == venv_path.as_posix()+ )+ finally:+ session.close()++[email protected]("zmq")+async def test_configured_venv_launches_editor_kernel_without_sandbox(+ tmp_path: Path,+) -> None:+ from marimo._session.managers.ipc import IPCKernelManagerImpl++ notebook = tmp_path / "notebook.py"+ notebook.write_text(+ "# /// script\n# [tool.marimo.venv]\n"+ f"# path = {str(Path(sys.prefix).as_posix())!r}\n# ///\n"+ )+ session = await SessionImpl.create(+ initialization_id=str(notebook),+ startup=SessionStartup(),+ session_consumer=None,+ mode=SessionMode.EDIT,+ app_metadata=AppMetadata(+ query_params={},+ filename=str(notebook),+ cli_args={},+ app_config=_AppConfig(),+ ),+ app_file_manager=AppFileManager(filename=str(notebook)),+ config_manager=get_default_config_manager(current_path=str(tmp_path)),+ virtual_file_storage=None,+ redirect_console_to_browser=False,+ ttl_seconds=None,+ auto_instantiate=False,+ sandbox=False,+ )+ try:+ manager = session._kernel_manager+ assert isinstance(manager, IPCKernelManagerImpl)+ assert manager.is_alive()+ assert manager.venv_python is not None+ assert Path(manager.venv_python).parent.parent == Path(sys.prefix)+ assert session.notebook_sandbox is None+ finally:+ session.close()++async def test_session_script_dotenv_reaches_the_kernel_config(tmp_path: Path,) -> None:diff --git a/tests/_session/managers/test_ipc.py b/tests/_session/managers/test_ipc.pyindex 895c33c3b9..d393fd3bab 100644--- a/tests/_session/managers/test_ipc.py+++ b/tests/_session/managers/test_ipc.py@@ -66,6 +66,7 @@ class TestIPCKernelManagerImpl:# Create IPCKernelManagerImpl without starting kernelkernel_manager = IPCKernelManagerImpl(+ sandbox=True,queue_manager=queue_manager,connection_info=connection_info,mode=SessionMode.EDIT,@@ -297,6 +298,7 @@ def _make_manager(filename: str | None = None) -> object:app_metadata = MagicMock()app_metadata.filename = filenamereturn IPCKernelManagerImpl(+ sandbox=True,queue_manager=IPCQueueManagerImpl(MagicMock()),connection_info=MagicMock(),mode=SessionMode.EDIT,@@ -554,6 +556,7 @@ async def test_startup_owns_kernel_process_and_pipes()queues, connection_info = QueueManager.create()manager = IPCKernelManagerImpl(+ sandbox=not configured,queue_manager=IPCQueueManagerImpl.from_ipc(queues),connection_info=connection_info,mode=SessionMode.EDIT,