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: auto-export ipynb from reload/remapping (#3994)
Myles Scolnick4302cc1623e9
diff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.pyindex d3e5d4ea2a..db96b2e5b9 100644--- a/marimo/_ast/cell_manager.py+++ b/marimo/_ast/cell_manager.py@@ -386,10 +386,13 @@ class CellManager:id_mapping = dict(zip(sorted_ids, current_ids))# Update the cell data in place- self._cell_data = {- new_id: self._cell_data[old_id]- for new_id, old_id in id_mapping.items()- }+ new_cell_data: dict[CellId_t, CellData] = {}+ for new_id, old_id in id_mapping.items():+ prev_cell_data = self._cell_data[old_id]+ prev_cell_data.cell_id = new_id+ new_cell_data[new_id] = prev_cell_data++ self._cell_data = new_cell_data# Add the new ids to the set, so we don't reuse them in the futurefor _id in sorted_ids:diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.pyindex da3ddc4371..40f107a912 100644--- a/marimo/_server/export/exporter.py+++ b/marimo/_server/export/exporter.py@@ -187,6 +187,9 @@ class Exporter:notebook["cells"] = []for cid in cell_ids:+ if cid not in graph.cells:+ LOGGER.warning("Cell %s not found in graph", cid)+ continuecell = graph.cells[cid]outputs: list[NotebookNode] = []diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.pyindex f6f7418e25..4ea0578e34 100644--- a/marimo/_server/file_manager.py+++ b/marimo/_server/file_manager.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport osimport pathlibimport shutil-from typing import Any, Optional+from typing import TYPE_CHECKING, Any, Optional, Unionfrom marimo import _loggersfrom marimo._ast import codegen@@ -24,14 +24,19 @@ from marimo._server.models.models import (from marimo._server.utils import canonicalize_filenamefrom marimo._types.ids import CellId_t+if TYPE_CHECKING:+ from pathlib import Path+LOGGER = _loggers.marimo_logger()class AppFileManager:def __init__(- self, filename: Optional[str], default_width: WidthType | None = None+ self,+ filename: Optional[Union[str, Path]],+ default_width: WidthType | None = None,) -> None:- self.filename = filename+ self.filename = str(filename) if filename else Noneself._default_width: WidthType | None = default_widthself.app = self._load_app(self.path)diff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.pyindex 1bd84b6bfe..f6c66d1b18 100644--- a/tests/_server/api/endpoints/test_export.py+++ b/tests/_server/api/endpoints/test_export.py@@ -2,6 +2,9 @@from __future__ import annotationsimport os+import shutil+import time+from pathlib import Pathfrom typing import TYPE_CHECKINGimport pytest@@ -9,8 +12,13 @@ import pytestfrom marimo import __version__from marimo._dependencies.dependencies import DependencyManagerfrom marimo._output.utils import uri_encode_component+from marimo._types.ids import SessionIdfrom tests._server.conftest import get_session_manager-from tests._server.mocks import token_header, with_read_session, with_session+from tests._server.mocks import (+ token_header,+ with_read_session,+ with_session,+)from tests.mocks import snapshotterif TYPE_CHECKING:@@ -18,7 +26,7 @@ if TYPE_CHECKING:snapshot = snapshotter(__file__)-SESSION_ID = "session-123"+SESSION_ID = SessionId("session-123")HEADERS = {"Marimo-Session-Id": SESSION_ID,**token_header("fake-token"),@@ -334,6 +342,98 @@ def test_auto_export_ipynb()+ not DependencyManager.nbformat.has(), reason="nbformat not installed"+)+@with_session(SESSION_ID)+def test_auto_export_ipynb_with_new_cell(+ client: TestClient, *, temp_marimo_file: str+) -> None:+ """Test that auto-exporting to ipynb works after creating and running a new cell.++ This test addresses the bug in https://github.com/marimo-team/marimo/issues/3992+ where cell ID inconsistency causes KeyError when auto-exporting as ipynb.+ """+ session = get_session_manager(client).get_session(SESSION_ID)+ assert session+ session.app_file_manager.filename = temp_marimo_file++ # First, create and run a cell with constant value 1+ create_cell_response = client.post(+ "/api/kernel/run",+ headers=HEADERS,+ json={+ "cell_ids": ["new_cell"],+ "codes": ["3.14"],+ },+ )+ assert create_cell_response.status_code == 200++ time.sleep(0.5)++ # Save the session+ save_response = client.post(+ "/api/kernel/save",+ headers=HEADERS,+ json={+ "cell_ids": ["new_cell"],+ "filename": temp_marimo_file,+ "codes": ["3.14"],+ "names": ["_"],+ "configs": [+ {+ "hideCode": True,+ "disabled": False,+ }+ ],+ },+ )+ assert save_response.status_code == 200, save_response.text++ # Clean up the marimo directory+ marimo_dir = Path(temp_marimo_file).parent / "__marimo__"+ shutil.rmtree(marimo_dir, ignore_errors=True)++ # Now attempt to auto-export as ipynb+ export_response = client.post(+ "/api/export/auto_export/ipynb",+ headers=HEADERS,+ json={+ "download": False,+ },+ )+ assert export_response.status_code == 200+ assert export_response.json() == {"success": True}++ # Verify the exported file exists+ assert marimo_dir.exists()++ # Verify the cell output is correct+ session = get_session_manager(client).get_session(SESSION_ID)+ assert session++ # Wait for the cell operation to be created+ timeout = 2+ start = time.time()+ cell_op = None+ while time.time() - start < timeout:+ if "new_cell" not in session.session_view.cell_operations:+ time.sleep(0.1)+ continue+ cell_op = session.session_view.cell_operations["new_cell"]+ if cell_op.output is not None:+ break+ assert cell_op+ assert cell_op.output is not None+ assert "3.14" in cell_op.output.data++ # Verify the ipynb file exists+ filename = Path(temp_marimo_file).name.replace(".py", ".ipynb")+ ipynb_path = marimo_dir / filename+ notebook = ipynb_path.read_text()+ assert "<pre style='font-size: 12px'>3.14</pre>" in notebook++@with_session(SESSION_ID)def test_export_html_with_script_config(client: TestClient) -> None:session = get_session_manager(client).get_session(SESSION_ID)diff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.pyindex fe9a3c3113..0d5004dfcb 100644--- a/tests/_server/api/endpoints/test_resume_session.py+++ b/tests/_server/api/endpoints/test_resume_session.py@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any, Optionalfrom marimo._config.manager import UserConfigManagerfrom marimo._messaging.ops import CellOp, KernelCapabilities, KernelReadyfrom marimo._server.sessions import Session+from marimo._types.ids import SessionIdfrom marimo._utils.parse_dataclass import parse_rawfrom tests._server.conftest import get_session_managerfrom tests._server.mocks import token_header@@ -67,7 +68,9 @@ def assert_kernel_ready_response(assert data.capabilities == expected.capabilities-def get_session(client: TestClient, session_id: str) -> Optional[Session]:+def get_session(+ client: TestClient, session_id: SessionId+) -> Optional[Session]:return get_session_manager(client).get_session(session_id)@@ -77,7 +80,7 @@ def test_refresh_session(client: TestClient) -> None:assert_kernel_ready_response(data, create_response({}))# Check the session still exists after closing the websocket- session = get_session(client, "123")+ session = get_session(client, SessionId("123"))assert sessionsession_view = session.session_viewdiff --git a/tests/_server/test_file_manager.py b/tests/_server/test_file_manager.pyindex 1cf2f80edd..603ae439d6 100644--- a/tests/_server/test_file_manager.py+++ b/tests/_server/test_file_manager.py@@ -16,6 +16,7 @@ from marimo._server.models.models import SaveNotebookRequestif TYPE_CHECKING:from collections.abc import Generator+ from pathlib import Pathsave_request = SaveNotebookRequest(cell_ids=["1"],@@ -452,3 +453,125 @@ def test_rename_with_special_chars(app_file_manager: AppFileManager) -> None:assert os.path.exists(new_path)finally:shutil.rmtree(temp_dir)+++def test_reload_reinitializes_graph(tmp_path: Path) -> None:+ """Test that reload() properly reinitializes the graph with new cells."""+ # Create a temporary file+ tmp_file = tmp_path / "test.py"++ # Initial content with one cell+ tmp_file.write_text(+ """+import marimo++app = marimo.App()++def cell1():+ x = 1+ return x++if __name__ == "__main__":+ app.run()+"""+ )++ cell_one = "Hbol"+ cell_two = "MJUe"++ # Create the file manager and load the app+ manager = AppFileManager(tmp_file)++ # Force initialization to create the graph+ assert manager.app._app._initialized is False+ assert manager.app.graph is not None+ assert manager.app._app._initialized is True++ # Check initial graph state+ cell_ids = list(manager.app.cell_manager.cell_ids())+ assert len(cell_ids) == 1+ assert cell_ids[0] == cell_one++ # Check the graph has the correct cells+ assert manager.app.graph.cells.keys() == {cell_one}+ assert manager.app.graph.get_defining_cells("x") == {cell_one}++ # Modify file with an additional cell+ tmp_file.write_text(+ """+import marimo++app = marimo.App()++def cell2():+ y = x + 1+ return y++def cell1():+ x = 1+ return x++if __name__ == "__main__":+ app.run()+"""+ )++ # Reload the app+ changed_cell_ids = manager.reload()+ assert changed_cell_ids == {cell_two}++ # Check that the graph was updated+ assert manager.app._app._initialized is False+ assert manager.app.graph is not None+ assert manager.app._app._initialized is True++ # Verify graph has both cells+ assert len(list(manager.app.graph.cells)) == 2++ # Verify edge exists between cell1 and cell2 (dependency)+ cell_ids = list(manager.app.cell_manager.cell_ids())+ assert cell_ids == [cell_two, cell_one]+ assert manager.app.cell_manager.get_cell_code(cell_one) == "x = 1"+ assert manager.app.cell_manager.get_cell_code(cell_two) == "y = x + 1"++ # Check that cell2 depends on cell1 in the graph+ assert manager.app.graph.get_defining_cells("x") == {cell_one}+ assert manager.app.graph.get_defining_cells("y") == {cell_two}++ # Modify the file to remove the dependency+ tmp_file.write_text(+ """+import marimo++app = marimo.App()++def cell2():+ y = 2 + 1+ return y++if __name__ == "__main__":+ app.run()+"""+ )++ # Reload the app+ changed_cell_ids = manager.reload()+ assert changed_cell_ids == {cell_one}++ # Verify cell_manager has only one cell+ cell_ids = list(manager.app.cell_manager.cell_ids())+ assert cell_ids == [cell_one]++ # Verify graph has only one cell+ graph_ids = list(manager.app.graph.cells)+ assert graph_ids == [cell_one]++ # Check that the graph was updated+ assert manager.app.graph.get_defining_cells("y") == {cell_one}++ # Clean up+ os.remove(tmp_file)