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.

enhancement: raise a UsageError on marimo edit --sandbox (#5511)

Akshay Agrawal072cca97ec97
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index b54929ba69..7d3f1e6de3 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -218,8 +218,9 @@ token_password_message = (
)
sandbox_message = (
- "Run the command in an isolated virtual environment using "
- "`uv run --isolated`. Requires `uv`."
+ "Run the notebook in an isolated environment, with dependencies tracked "
+ "via PEP 723 inline metadata. If already declared, dependencies will "
+ "install automatically. Requires uv."
)
@@ -395,6 +396,19 @@ edit_help_msg = "\n".join(
type=bool,
help=sandbox_message,
)
+ "--dangerous-sandbox/--no-dangerous-sandbox",
+ is_flag=True,
+ default=None,
+ show_default=False,
+ type=bool,
+ hidden=True,
+ help="""Enables the usage of package sandboxing when running a multi-edit
+notebook server. This behavior can lead to surprising and unintended consequences,
+such as incorrectly overwriting package requirements or failing to write out
+requirements. These and other issues are described in
+https://github.com/marimo-team/marimo/issues/5219.""",
+)
@click.option("--profile-dir", default=None, type=str, hidden=True)
@click.option(
"--watch",
@@ -444,6 +458,7 @@ def edit(
allow_origins: Optional[tuple[str, ...]],
skip_update_check: bool,
sandbox: Optional[bool],
+ dangerous_sandbox: Optional[bool],
profile_dir: Optional[str],
watch: bool,
skew_protection: bool,
@@ -473,13 +488,39 @@ def edit(
)
return
- # Set default, if not provided
+ if dangerous_sandbox and (name is None or os.path.isdir(name)):
+ sandbox = True
+ click.echo(
+ click.style(
+ "Warning: Using sandbox with multi-notebook edit servers is dangerous.\n",
+ fg="yellow",
+ )
+ + "Notebook dependencies may not be respected, may not be written, and may be overwritten.\n"
+ + "Learn more: https://github.com/marimo-team/marimo/issues/5219l.\n",
+ err=True,
+ )
+
if sandbox is None:
+ # When the sandbox flag is omitted we infer whether to
+ # to start in sandbox mode by examining the notebook file and
+ # prompting the user.
from marimo._cli.sandbox import maybe_prompt_run_in_sandbox
sandbox = maybe_prompt_run_in_sandbox(name)
+ elif (
+ sandbox
+ and not dangerous_sandbox
+ and (name is None or os.path.isdir(name))
+ ):
+ raise click.UsageError(
+ """marimo's package sandbox requires a notebook name:
- if sandbox:
+ * marimo edit --sandbox my_notebook.py
+
+ Multi-notebook sandboxed servers (marimo edit --sandbox) are not supported.
+ Follow this issue at: https://github.com/marimo-team/marimo/issues/2598."""
+ )
+ elif sandbox:
from marimo._cli.sandbox import run_in_sandbox
# TODO: consider adding recommended as well
diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.py
index 2895b68583..0e16a3e7b7 100644
--- a/marimo/_cli/sandbox.py
+++ b/marimo/_cli/sandbox.py
@@ -244,6 +244,8 @@ def construct_uv_command(
cmd = ["marimo"] + args
if "--sandbox" in cmd:
cmd.remove("--sandbox")
+ if "--dangerous-sandbox" in cmd:
+ cmd.remove("--dangerous-sandbox")
pyproject = (
PyProjectReader.from_filename(name)
diff --git a/tests/_cli/test_cli.py b/tests/_cli/test_cli.py
index 8cb12308e3..f60ae10567 100644
--- a/tests/_cli/test_cli.py
+++ b/tests/_cli/test_cli.py
@@ -30,6 +30,7 @@ from marimo._server.templates.templates import get_version
from marimo._utils.config.config import ROOT_DIR as CONFIG_ROOT_DIR
from marimo._utils.platform import is_windows
from marimo._utils.toml import read_toml
+from tests.utils import try_assert_n_times
if TYPE_CHECKING:
from collections.abc import Generator, Iterator
@@ -579,6 +580,110 @@ def test_cli_sandbox_edit_new_file() -> None:
_check_contents(p, b"edit", contents)
[email protected](not HAS_UV, reason="uv is required for sandbox tests")
+def test_cli_sandbox_edit_none_not_supported() -> None:
+ port = _get_port()
+ p = subprocess.Popen(
+ [
+ "marimo",
+ "edit",
+ "-p",
+ str(port),
+ "--headless",
+ "--no-token",
+ "--sandbox",
+ ],
+ stderr=subprocess.PIPE,
+ )
+
+ def _assert():
+ assert p.returncode != 0
+
+ try_assert_n_times(5, _assert)
+ assert p.stderr is not None
+ assert "not supported" in p.stderr.read().decode()
+
+
[email protected](not HAS_UV, reason="uv is required for sandbox tests")
+def test_cli_sandbox_edit_directory_not_supported() -> None:
+ port = _get_port()
+ p = subprocess.Popen(
+ [
+ "marimo",
+ "edit",
+ "../",
+ "-p",
+ str(port),
+ "--headless",
+ "--no-token",
+ "--sandbox",
+ ],
+ stderr=subprocess.PIPE,
+ )
+
+ def _assert():
+ assert p.returncode != 0
+
+ try_assert_n_times(5, _assert)
+ assert p.stderr is not None
+ assert "not supported" in p.stderr.read().decode()
+
+
[email protected](not HAS_UV, reason="uv is required for sandbox tests")
+def test_cli_edit_none_dangerous_sandbox_allowed() -> None:
+ # sandbox is disallowed in a multi-notebook edit server,
+ # but can be overridden with --dangerous-sandbox.
+ port = _get_port()
+ p = subprocess.Popen(
+ [
+ "marimo",
+ "edit",
+ "--dangerous-sandbox",
+ "-p",
+ str(port),
+ "--headless",
+ "--no-token",
+ "--skip-update-check",
+ ]
+ )
+ contents = _try_fetch(port)
+ _check_contents(p, b'"mode": "home"', contents)
+ _check_contents(
+ p,
+ f'"version": "{get_version()}"'.encode(),
+ contents,
+ )
+ _check_contents(p, b'"serverToken": ', contents)
+
+
[email protected](not HAS_UV, reason="uv is required for sandbox tests")
+def test_cli_edit_directory_dangerous_sandbox_allowed() -> None:
+ # sandbox is disallowed in a multi-notebook edit server,
+ # but can be overridden with --dangerous-sandbox.
+ port = _get_port()
+ p = subprocess.Popen(
+ [
+ "marimo",
+ "edit",
+ "../",
+ "--dangerous-sandbox",
+ "-p",
+ str(port),
+ "--headless",
+ "--no-token",
+ "--skip-update-check",
+ ]
+ )
+ contents = _try_fetch(port)
+ _check_contents(p, b'"mode": "home"', contents)
+ _check_contents(
+ p,
+ f'"version": "{get_version()}"'.encode(),
+ contents,
+ )
+ _check_contents(p, b'"serverToken": ', contents)
+
+
@pytest.mark.skipif(is_windows(), reason="Windows will prompt for Docker")
def test_cli_edit_by_url() -> None:
port = _get_port()
@@ -891,13 +996,41 @@ def test_cli_with_custom_pyproject_config(tmp_path: Path) -> None:
finally:
p.kill()
- # marimo edit --sandbox, in the directory with pyproject.toml
+
+# Test sandbox with config for vscode compatibility
[email protected](not HAS_UV, reason="uv is required for sandbox tests")
+def test_cli_with_custom_pyproject_config_no_file(tmp_path: Path) -> None:
+ # Create a custom pyproject.toml with special marimo config
+ pyproject_path = tmp_path / "pyproject.toml"
+ pyproject_content = """
+ [tool.marimo]
+ formatting = {line_length = 111}
+
+ [tool.marimo.runtime]
+ auto_instantiate = false
+
+ [tool.marimo.package_management]
+ manager = "pip"
+ """
+ pyproject_path.write_text(pyproject_content)
+
+ def assert_custom_config(contents: bytes | None) -> None:
+ assert contents is not None
+ # Verify that the custom config is applied
+ assert b'"line_length": 111' in contents
+ assert b'"auto_instantiate": false' in contents
+ # Verify that the package manager is switch to uv because we are running in a sandbox
+ # TODO: fix this, it does not get overridden in tests (maybe it is using a different marimo version that the one in CI)
+ # assert b'"manager": "uv"' in contents
+
+ # marimo edit --dangerous-sandbox, in the directory with pyproject.toml,
+ # for vscode extension compatibility
port = _get_port()
p = subprocess.Popen(
[
"marimo",
"edit",
- "--sandbox",
+ "--dangerous-sandbox",
"-p",
str(port),
"--headless",
diff --git a/tests/_server/api/endpoints/test_files.py b/tests/_server/api/endpoints/test_files.py
index 3e9e3045eb..bf4d3a9698 100644
--- a/tests/_server/api/endpoints/test_files.py
+++ b/tests/_server/api/endpoints/test_files.py
@@ -3,9 +3,8 @@ from __future__ import annotations
import os
import random
-import time
from pathlib import Path
-from typing import TYPE_CHECKING, Callable
+from typing import TYPE_CHECKING
import pytest
@@ -15,6 +14,7 @@ from tests._server.mocks import (
with_session,
with_websocket_session,
)
+from tests.utils import try_assert_n_times
if TYPE_CHECKING:
from starlette.testclient import TestClient, WebSocketTestSession
@@ -26,18 +26,6 @@ HEADERS = {
}
-def _try_assert_n_times(n: int, assert_fn: Callable[[], None]) -> None:
- n_tries = 0
- while n_tries <= n - 1:
- try:
- assert_fn()
- return
- except Exception:
- n_tries += 1
- time.sleep(0.1)
- assert_fn()
-
-
@with_session(SESSION_ID)
def test_rename(client: TestClient) -> None:
current_filename = get_session_manager(
@@ -64,7 +52,7 @@ def test_rename(client: TestClient) -> None:
def _new_path_exists():
assert new_path.exists()
- _try_assert_n_times(5, _new_path_exists)
+ try_assert_n_times(5, _new_path_exists)
@pytest.mark.flaky(reruns=5)
@@ -111,7 +99,7 @@ def test_save_file(client: TestClient) -> None:
assert "@app.cell(hide_code=True)" in file_contents
assert "my_cell" in file_contents
- _try_assert_n_times(5, _assert_contents)
+ try_assert_n_times(5, _assert_contents)
# save back
response = client.post(
@@ -179,7 +167,7 @@ def test_save_with_header(client: TestClient) -> None:
assert "@app.cell(hide_code=True)" in file_contents
assert "my_cell" in file_contents
- _try_assert_n_times(5, _assert_contents)
+ try_assert_n_times(5, _assert_contents)
@pytest.mark.flaky(reruns=5)
@@ -233,7 +221,7 @@ def test_save_with_invalid_file(client: TestClient) -> None:
"Header was not removed"
)
- _try_assert_n_times(5, _assert_contents)
+ try_assert_n_times(5, _assert_contents)
@with_session(SESSION_ID)
@@ -271,7 +259,7 @@ def test_save_app_config(client: TestClient) -> None:
file_contents = path.read_text()
assert 'marimo.App(width="medium"' not in file_contents
- _try_assert_n_times(5, _wait_for_file_reset)
+ try_assert_n_times(5, _wait_for_file_reset)
response = client.post(
"/api/kernel/save_app_config",
@@ -287,7 +275,7 @@ def test_save_app_config(client: TestClient) -> None:
file_contents = path.read_text()
assert 'marimo.App(width="medium"' in file_contents
- _try_assert_n_times(5, _assert_contents)
+ try_assert_n_times(5, _assert_contents)
@with_session(SESSION_ID)
@@ -318,7 +306,7 @@ def test_copy_file(client: TestClient) -> None:
assert "import marimo as mo" in file_contents
assert 'marimo.App(width="full"' in file_contents
- _try_assert_n_times(5, _assert_contents)
+ try_assert_n_times(5, _assert_contents)
@with_websocket_session(SESSION_ID)
diff --git a/tests/utils.py b/tests/utils.py
new file mode 100644
index 0000000000..6d92e3e378
--- /dev/null
+++ b/tests/utils.py
@@ -0,0 +1,23 @@
+from __future__ import annotations
+
+import time
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from typing import Callable
+
+
+def try_assert_n_times(n: int, assert_fn: Callable[[], None]) -> None:
+ """Attempt an assert multiple times.
+
+ Sleeps between each attempt.
+ """
+ n_tries = 0
+ while n_tries <= n - 1:
+ try:
+ assert_fn()
+ return
+ except Exception:
+ n_tries += 1
+ time.sleep(0.1)
+ assert_fn()