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
fix: slurm script regression and docs/examples update (#10469)
Dylan Madisettif1b3678a88d9
diff --git a/docs/guides/deploying/deploying_slurm.md b/docs/guides/deploying/deploying_slurm.mdindex c0689e1669..04f4048c41 100644--- a/docs/guides/deploying/deploying_slurm.md+++ b/docs/guides/deploying/deploying_slurm.md@@ -134,7 +134,7 @@ this lets you create fully self-contained notebooks./// tab | Interactive development```python-#!/usr/bin/env -S python -m marimo edit --sandbox+#!/usr/bin/env -S uvx marimo edit --sandbox#SBATCH --job-name=marimo-job#SBATCH --output=marimo-%j.out#SBATCH --cpus-per-task=4@@ -166,7 +166,7 @@ if __name__ == "__main__":/// tab | Batch job```-#!/usr/bin/env -S python+#!/usr/bin/env -S uv run --script#SBATCH --job-name=marimo-job#SBATCH --output=marimo-%j.out#SBATCH --cpus-per-task=4@@ -207,6 +207,13 @@ sbatch notebook.pySandboxing requires [uv](https://docs.astral.sh/uv/getting-started/installation/) to be installed.+/// admonition | Why `--script`?++Slurm runs a spooled copy of your submitted file with no extension. The+`--script` flag tells `uv` to treat it as a script.++///+## Learn more- [Slurm examples](https://github.com/marimo-team/marimo/tree/main/examples/slurm) - Complete working examplesdiff --git a/examples/slurm/README.md b/examples/slurm/README.mdnew file mode 100644index 0000000000..9ae59cf8ff--- /dev/null+++ b/examples/slurm/README.md@@ -0,0 +1,47 @@+# Slurm examples++Working examples for running marimo notebooks on Slurm-managed clusters,+including Slurm-on-Kubernetes setups like SUNK. See the+[Slurm deployment guide](https://docs.marimo.io/guides/deploying/deploying_slurm/)+for the full walkthrough.++Both patterns require [uv](https://docs.astral.sh/uv/getting-started/installation/)+on `PATH` (Slurm propagates the submission shell's environment to the job by+default).++## Interactive: marimo editor on a compute node++[`run_marimo.sh`](run_marimo.sh) opens+[`submit_notebook.py`](submit_notebook.py); swap in your own notebook path+to edit something else.++```bash+sbatch run_marimo.sh+squeue -u $USER # find the compute node+ssh -L 3000:NODE:3000 you@cluster # tunnel from your laptop+# open http://localhost:3000+```++## Batch: a notebook that is its own Slurm job++[`submit_notebook.py`](submit_notebook.py) is simultaneously a marimo+notebook, a Python script, and an sbatch submission — the `#SBATCH`+directives, the dependencies (PEP 723), and the code travel in one file:++```bash+chmod +x submit_notebook.py+sbatch submit_notebook.py --n 500000+```++The `--script` flag in the shebang lets `uv` run Slurm's spooled,+extensionless copy of the file.++Tips for shared clusters:++- `uv`'s wheel cache lives in `~/.cache/uv`; point `UV_CACHE_DIR` at a shared+ or project filesystem so compute nodes reuse downloads.+- If your home and cache live on different mounts, set `UV_LINK_MODE=copy`.+- `mo.persistent_cache` writes to `__marimo__/cache/` next to the notebook. If+ that directory is not writable, it will write under the job's working+ directory instead. If you use the cache, consider launching jobs from a shared+ file system, such that resubmissions will correctly skip completed work.diff --git a/examples/slurm/run_marimo.sh b/examples/slurm/run_marimo.shnew file mode 100755index 0000000000..1de15215f0--- /dev/null+++ b/examples/slurm/run_marimo.sh@@ -0,0 +1,11 @@+#!/usr/bin/env bash+#SBATCH --job-name=marimo+#SBATCH --output=marimo-%j.out+#SBATCH --cpus-per-task=4+#SBATCH --mem=16GB+#SBATCH --time=4:00:00++# Runs the marimo editor on a compute node against the *original* notebook+# file. Connect from your laptop with:+# ssh -L 3000:NODE:3000 you@cluster+uvx marimo edit --sandbox submit_notebook.py --headless --port 3000diff --git a/examples/slurm/submit_notebook.py b/examples/slurm/submit_notebook.pynew file mode 100755index 0000000000..8b2de0ee41--- /dev/null+++ b/examples/slurm/submit_notebook.py@@ -0,0 +1,83 @@+#!/usr/bin/env -S uv run --script+#SBATCH --job-name=marimo-batch+#SBATCH --output=marimo-%j.out+#SBATCH --cpus-per-task=4+#SBATCH --mem=16GB+#SBATCH --time=00:30:00++# /// script+# requires-python = ">=3.12"+# dependencies = [+# "marimo",+# "numpy",+# ]+# ///++import marimo++__generated_with = "0.23.16"+app = marimo.App(app_title="Slurm batch example")++with app.setup:+ import argparse+ import time++ import marimo as mo+ import numpy as np++[email protected](hide_code=True)+def _():+ mo.md("""+ # A notebook / Slurm job++ This file is simultaneously:++ * a marimo notebook — `marimo edit submit_notebook.py`+ * a Python script — `uv run submit_notebook.py --n 500000`+ * a Slurm job — `chmod +x submit_notebook.py && sbatch submit_notebook.py`++ The `#SBATCH` directives, the dependencies (PEP 723), and the code all+ live in this one file.+ """)+ return+++def _():+ parser = argparse.ArgumentParser(description="Slurm batch example")+ parser.add_argument("--n", type=int, default=100_000)+ parser.add_argument("--seed", type=int, default=42)++ if mo.running_in_notebook():+ _args = parser.parse_args([])+ else:+ _args = parser.parse_args()+ # Unpack into plain values: the cache keys on the values a cached cell+ # reads, and primitives hash by content (a Namespace does not).+ n, seed = _args.n, _args.seed+ return n, seed+++def _(n, seed):+ # Stand-in for real work. The cache persists to disk, so a resubmitted+ # job with the same arguments restores instead of recomputing, while+ # new values of `n` or `seed` recompute.+ with mo.persistent_cache("monte_carlo_pi"):+ _start = time.perf_counter()+ _rng = np.random.default_rng(seed)+ _points = _rng.random((n, 2))+ pi_estimate = 4.0 * float(((_points**2).sum(axis=1) <= 1.0).mean())+ elapsed = time.perf_counter() - _start+ return elapsed, pi_estimate+++def _(elapsed, n, pi_estimate):+ print(f"pi ~= {pi_estimate:.6f} (n={n:,}, {elapsed:.2f}s)")+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_ast/load.py b/marimo/_ast/load.pyindex c29911b2f0..4292cf7431 100644--- a/marimo/_ast/load.py+++ b/marimo/_ast/load.py@@ -123,13 +123,12 @@ def get_notebook_status(filename: str) -> LoadResult:if not contents:return LoadResult(status="empty", contents=contents)- notebook: NotebookSerialization | None = None- handler = get_notebook_serializer(path)+ # NB. Slurm executes sbatch scripts from a spooled copy of the submitted+ # file, which has no extension — fall back to the Python serializer.+ handler = get_notebook_serializer(path, contents, default=".py")notebook = handler.deserialize(contents, filepath=filename)# NB. A invalid notebook can still be opened.- if notebook is None:- return LoadResult(status="empty", contents=contents)if not notebook.valid:if is_non_marimo_python_script(notebook):return LoadResult(diff --git a/marimo/_save/stores/file.py b/marimo/_save/stores/file.pyindex 5aeb2cc4e5..2adc31d742 100644--- a/marimo/_save/stores/file.py+++ b/marimo/_save/stores/file.py@@ -1,12 +1,19 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations+import osimport refrom pathlib import Path+from marimo import _loggersfrom marimo._runtime.runtime import notebook_dirfrom marimo._save.stores.store import Store-from marimo._utils.paths import notebook_output_dir+from marimo._utils.paths import MARIMO_DIR_NAME, notebook_output_dir++LOGGER = _loggers.marimo_logger()++# Resolves against the working directory as a fallback.+FALLBACK_SAVE_PATH = Path(MARIMO_DIR_NAME, "cache")def export_manifest_name(notebook_filename: str | None) -> str:@@ -25,6 +32,16 @@ def _valid_path(path: Path) -> bool:return path.exists() and path.stat().st_size > 0+def _writable_dir(path: Path) -> bool:+ """Whether `path` is a writable directory. Creates it if absent."""+ try:+ path.mkdir(parents=True, exist_ok=True)+ except OSError:+ return False+ # NB. mkdir is a no-op on an existing directory, whatever its mode.+ return os.access(path, os.W_OK | os.X_OK)++class FileStore(Store):def __init__(self, save_path: str | None = None) -> None:# Defer default path resolution until first use so that the runtime@@ -41,10 +58,22 @@ class FileStore(Store):return self._resolved_save_pathdef _default_save_path(self) -> Path:- if (root := notebook_dir()) is not None:- return notebook_output_dir(root) / "cache"- # This can happen if the notebook file is unnamed.- return Path("__marimo__", "cache")+ root = notebook_dir()+ if root is None:+ return FALLBACK_SAVE_PATH++ # Probe the write target, which `sys.pycache_prefix` can move out of+ # the notebook's directory.+ target = notebook_output_dir(root) / "cache"+ if _writable_dir(target):+ return target++ LOGGER.warning(+ "Could not write to the cache directory %s. Caching to %s instead.",+ target,+ FALLBACK_SAVE_PATH.resolve(),+ )+ return FALLBACK_SAVE_PATHdef _init_save_path(self) -> None:self.save_path.mkdir(parents=True, exist_ok=True)diff --git a/marimo/_session/notebook/serializer.py b/marimo/_session/notebook/serializer.pyindex 92345b4488..f9d8ba4998 100644--- a/marimo/_session/notebook/serializer.py+++ b/marimo/_session/notebook/serializer.py@@ -6,6 +6,7 @@ from __future__ import annotationsfrom pathlib import Pathfrom typing import Protocol+from marimo._ast.parse import MarimoFileError, is_non_marimo_python_scriptfrom marimo._schemas.serialization import (AppInstantiation,NotebookSerializationV1,@@ -130,24 +131,52 @@ DEFAULT_NOTEBOOK_SERIALIZERS = {}-def get_notebook_serializer(path: Path) -> NotebookSerializer:+def get_notebook_serializer(+ path: Path,+ contents: str | None = None,+ default: str | None = None,+) -> NotebookSerializer:"""Get the appropriate notebook serializer for a file.Args:path: File path+ contents: Optional file contents. If the contents are a marimo+ notebook, a path with no suffix resolves to the `default`+ serializer.+ default: Suffix of the serializer to fall back toReturns:Appropriate notebook serializerRaises:- ValueError: If no notebook serializer supports the file format+ ValueError: If no notebook serializer supports the file"""# Ensure path is a Path objectif not isinstance(path, Path):path = Path(path)- ext = path.suffix- handler = DEFAULT_NOTEBOOK_SERIALIZERS.get(ext)+ handler = DEFAULT_NOTEBOOK_SERIALIZERS.get(path.suffix)+ # E.g. ./script (no suffix) with contents that are a marimo notebook.+ if (+ handler is None+ and path.suffix == ""+ and default is not None+ and contents is not None+ ):+ # Certain runners (like sbatch) may pass a script with no suffix. If the+ # contents are a marimo notebook, we can use the default (python) serializer.+ fallback = DEFAULT_NOTEBOOK_SERIALIZERS.get(default)+ if fallback is not None:+ try:+ # Relatively unusual path, so full deserialization seems+ # acceptable.+ notebook = fallback.deserialize(contents, filepath=str(path))+ if not is_non_marimo_python_script(notebook):+ handler = fallback+ except MarimoFileError:+ # Parses, but declares no `marimo.App`. Reject it like any+ # other unsupported file.+ passif handler is None:raise ValueError(f"No notebook serializer found for {path}. Supported extensions: {list(DEFAULT_NOTEBOOK_SERIALIZERS.keys())}"diff --git a/tests/_ast/test_load.py b/tests/_ast/test_load.pyindex b592fd8f6e..e5554aed96 100644--- a/tests/_ast/test_load.py+++ b/tests/_ast/test_load.py@@ -451,3 +451,45 @@ class TestGetStatus:load.get_notebook_status(get_filepath(filename)).status== expected_status)+++def test_extensionless_marimo_notebook(tmp_path):+ """A marimo notebook without a file extension still parses.++ Slurm executes sbatch scripts from a spooled, extensionless copy of the+ submitted file.+ """+ spool_path = tmp_path / "slurm_script"+ spool_path.write_text(+ """import marimo++__generated_with = "0.23.16"+app = marimo.App()+++def _():+ x = 1+ return (x,)+++if __name__ == "__main__":+ app.run()+""",+ encoding="utf-8",+ )++ result = load.get_notebook_status(str(spool_path))++ assert result.status == "valid"+ assert result.notebook is not None+ assert len(result.notebook.cells) == 1+++def test_extensionless_non_marimo_file_still_rejected(tmp_path):+ """The extensionless fallback only applies to marimo notebooks."""+ path = tmp_path / "some_script"+ path.write_text("print('not a notebook')\n", encoding="utf-8")++ with pytest.raises(ValueError, match="No notebook serializer"):+ load.get_notebook_status(str(path))diff --git a/tests/_save/stores/test_file.py b/tests/_save/stores/test_file.pyindex 9427b26074..ee7856c7ff 100644--- a/tests/_save/stores/test_file.py+++ b/tests/_save/stores/test_file.py@@ -2,9 +2,19 @@from __future__ import annotations+import logging+from pathlib import Path++import marimo._save.stores.file as file_mod+from marimo import _loggersfrom marimo._save.stores.file import FileStore+def _propagate_marimo_logs(monkeypatch) -> None:+ """Let `caplog` see marimo's logger, which does not propagate by default."""+ monkeypatch.setattr(_loggers.marimo_logger(), "propagate", True)++class TestFileStore:def test_init_doesnt_make_file(self, tmp_path) -> None:"""Test that initializing FileStore does not create a file."""@@ -51,3 +61,69 @@ class TestFileStore:# Accessing the property triggers resolution._ = store.save_pathassert store._resolved_save_path is not None+++class TestDefaultSavePath:+ def test_writable_notebook_dir(self, tmp_path, monkeypatch) -> None:+ """The cache anchors next to the notebook when its directory is writable."""+ monkeypatch.setattr(file_mod, "notebook_dir", lambda: tmp_path)++ path = FileStore()._default_save_path()++ assert path == tmp_path / "__marimo__" / "cache"++ def test_unwritable_target_falls_back_to_cwd(+ self, tmp_path, monkeypatch+ ) -> None:+ """A cache directory that cannot be created anchors to the working directory."""+ monkeypatch.setattr(file_mod, "notebook_dir", lambda: tmp_path)++ def deny_mkdir(self: Path, *_args: object, **_kwargs: object) -> None:+ raise PermissionError(f"read-only: {self}")++ monkeypatch.setattr(Path, "mkdir", deny_mkdir)++ path = FileStore()._default_save_path()++ assert path == Path("__marimo__", "cache")++ def test_existing_read_only_target_falls_back_to_cwd(+ self, tmp_path, monkeypatch+ ) -> None:+ """An existing cache directory that is not writable anchors to the working directory."""+ monkeypatch.setattr(file_mod, "notebook_dir", lambda: tmp_path)+ (tmp_path / "__marimo__" / "cache").mkdir(parents=True)+ monkeypatch.setattr(file_mod.os, "access", lambda *_args: False)++ path = FileStore()._default_save_path()++ assert path == Path("__marimo__", "cache")++ def test_fallback_is_warned_about(+ self, tmp_path, monkeypatch, caplog+ ) -> None:+ """The warning names both directories.++ Otherwise the move reads as a cache miss.+ """+ monkeypatch.setattr(file_mod, "notebook_dir", lambda: tmp_path)+ (tmp_path / "__marimo__" / "cache").mkdir(parents=True)+ monkeypatch.setattr(file_mod.os, "access", lambda *_args: False)+ _propagate_marimo_logs(monkeypatch)++ with caplog.at_level(logging.WARNING):+ FileStore()._default_save_path()++ assert str(tmp_path / "__marimo__" / "cache") in caplog.text+ assert str(Path("__marimo__", "cache").resolve()) in caplog.text++ def test_unnamed_notebook_does_not_warn(self, monkeypatch, caplog) -> None:+ """No warning: an unnamed notebook never had a directory to leave."""+ monkeypatch.setattr(file_mod, "notebook_dir", lambda: None)+ _propagate_marimo_logs(monkeypatch)++ with caplog.at_level(logging.WARNING):+ path = FileStore()._default_save_path()++ assert path == Path("__marimo__", "cache")+ assert caplog.text == ""diff --git a/tests/_save/test_extensionless_script.py b/tests/_save/test_extensionless_script.pynew file mode 100644index 0000000000..764322dd07--- /dev/null+++ b/tests/_save/test_extensionless_script.py@@ -0,0 +1,59 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import subprocess+import sys+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from pathlib import Path++NOTEBOOK_SOURCE = """import marimo++app = marimo.App()++with app.setup:+ import marimo as mo+++def _():+ with mo.persistent_cache("extensionless"):+ print("computed")+ value = 42+ print(f"value={value}")+ return+++if __name__ == "__main__":+ app.run()+"""+++def test_persistent_cache_in_extensionless_script(tmp_path: Path) -> None:+ """`mo.persistent_cache` works when the notebook runs from a spool copy.++ Slurm executes sbatch scripts from an extensionless copy of the submitted+ file. The cache block must still resolve its enclosing cell.+ """+ spool_path = tmp_path / "slurm_script"+ spool_path.write_text(NOTEBOOK_SOURCE, encoding="utf-8")++ for run in range(2):+ result = subprocess.run(+ [sys.executable, str(spool_path)],+ capture_output=True,+ text=True,+ cwd=tmp_path,+ timeout=120,+ )+ assert result.returncode == 0, (run, result.stderr)+ assert "value=42" in result.stdout+ # The first run computes; the second restores from the cache, so+ # the block body must not re-execute.+ block_ran = "computed" in result.stdout+ assert block_ran == (run == 0), (run, result.stdout)++ cache_dir = tmp_path / "__marimo__" / "cache"+ assert cache_dir.is_dir()+ assert any(cache_dir.iterdir())diff --git a/tests/_session/notebook/test_serializer.py b/tests/_session/notebook/test_serializer.pyindex 519dcaa451..9624a1bd92 100644--- a/tests/_session/notebook/test_serializer.py+++ b/tests/_session/notebook/test_serializer.py@@ -7,6 +7,7 @@ from pathlib import Pathimport pytest+from marimo._ast.parse import SCANNER_UNPARSABLE_CELL_VIOLATIONfrom marimo._schemas.serialization import (AppInstantiation,CellDef,@@ -313,6 +314,64 @@ class TestGetFormatHandler:assert ".md" in DEFAULT_NOTEBOOK_SERIALIZERSassert ".qmd" in DEFAULT_NOTEBOOK_SERIALIZERS+ def test_default_resolves_extensionless_marimo_notebook(+ self, tmp_path: Path+ ) -> None:+ path = tmp_path / "slurm_script"+ contents = (+ "import marimo\n\n"+ "app = marimo.App()\n\n\n"+ "@app.cell\n"+ "def _():\n"+ " x = 1\n"+ " return\n"+ )++ handler = get_notebook_serializer(path, contents, default=".py")++ assert isinstance(handler, PythonNotebookSerializer)++ def test_default_rejects_extensionless_non_marimo_contents(+ self, tmp_path: Path+ ) -> None:+ path = tmp_path / "slurm_script"++ with pytest.raises(ValueError, match="No notebook serializer found"):+ get_notebook_serializer(path, "print('plain')", default=".py")++ def test_default_requires_opt_in(self, tmp_path: Path) -> None:+ path = tmp_path / "slurm_script"+ contents = "import marimo\n\napp = marimo.App()\n"++ with pytest.raises(ValueError, match="No notebook serializer found"):+ get_notebook_serializer(path, contents)++ def test_default_resolves_notebook_with_syntax_error(+ self, tmp_path: Path+ ) -> None:+ """A syntax error yields a broken notebook, not an unsupported format.++ Parsing recovers from syntax errors instead of raising, so the probe+ still recognizes the contents.+ """+ path = tmp_path / "slurm_script"+ contents = (+ "import marimo\n\n"+ "app = marimo.App()\n\n\n"+ "@app.cell\n"+ "def _():\n"+ " x = (1\n"+ )++ handler = get_notebook_serializer(path, contents, default=".py")++ assert isinstance(handler, PythonNotebookSerializer)+ notebook = handler.deserialize(contents, filepath=str(path))+ assert any(+ violation.description == SCANNER_UNPARSABLE_CELL_VIOLATION+ for violation in notebook.violations+ )+class TestDeserializationWithFilenames:"""Test that filenames are propagated through the deserialization chain."""