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 `_code_mode` cell ID collisions on large notebooks (#8951)
Trevor Manz010cac018828
diff --git a/marimo/_ast/cell_id.py b/marimo/_ast/cell_id.pyindex 16f1db9204..dee16eca99 100644--- a/marimo/_ast/cell_id.py+++ b/marimo/_ast/cell_id.py@@ -9,9 +9,9 @@ from marimo._types.ids import CellId_tclass CellIdGenerator:- def __init__(self, prefix: str = "") -> None:+ def __init__(self, prefix: str = "", seed: int | None = None) -> None:self.prefix = prefix- self.random_seed = random.Random(42)+ self.random_seed = random.Random(seed)self.seen_ids: set[CellId_t] = set()def create_cell_id(self) -> CellId_t:diff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.pyindex 4d84e2ec51..1712b46ca5 100644--- a/marimo/_ast/cell_manager.py+++ b/marimo/_ast/cell_manager.py@@ -70,7 +70,7 @@ class CellManager:self._cell_data: dict[CellId_t, CellData] = {}self.prefix = prefixself.unparsable = False- self._cell_id_generator = CellIdGenerator(prefix)+ self._cell_id_generator = CellIdGenerator(prefix, seed=42)def create_cell_id(self) -> CellId_t:"""Create a new unique cell ID.diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.pyindex f18e8a5b40..52b32d0296 100644--- a/marimo/_code_mode/_context.py+++ b/marimo/_code_mode/_context.py@@ -250,10 +250,11 @@ class AsyncCodeModeContext:# Track cell IDs added during this batch so subsequent ops# can reference them before they exist in the graph.self._pending_adds: dict[CellId_t, _AddOp] = {}- # ID generator for new cells — seeded with existing IDs to- # avoid collisions.- self._id_generator = CellIdGenerator()- self._id_generator.seen_ids = set(kernel.graph.cells.keys())+ # ID generator for new cells — seed=None uses OS entropy so we+ # never replay a prior session's ID sequence. seen_ids from the+ # document prevents collisions with cells already on disk.+ self._id_generator = CellIdGenerator(seed=None)+ self._id_generator.seen_ids = set(document.cell_ids)self._packages_to_install: list[str] = []self._ui_updates: list[tuple[UIElementId, Any]] = []self._cells_to_run: set[CellId_t] = set()diff --git a/marimo/_convert/notebook.py b/marimo/_convert/notebook.pyindex 3b20fc9a06..4e51a7956d 100644--- a/marimo/_convert/notebook.py+++ b/marimo/_convert/notebook.py@@ -31,7 +31,7 @@ def convert_from_ir_to_notebook_v1(Returns:NotebookV1: The notebook v1."""- cell_id_generator = CellIdGenerator()+ cell_id_generator = CellIdGenerator(seed=42)cells: list[NotebookCell] = []for i, data in enumerate(notebook_ir.cells):if isinstance(data, SetupCell) or (diff --git a/tests/_code_mode/test_context.py b/tests/_code_mode/test_context.pyindex 7d49f57af8..05a948f6c5 100644--- a/tests/_code_mode/test_context.py+++ b/tests/_code_mode/test_context.py@@ -13,6 +13,7 @@ import pytestfrom inline_snapshot import snapshotfrom marimo._ast.cell import CellConfig+from marimo._ast.cell_id import CellIdGeneratorfrom marimo._code_mode._context import AsyncCodeModeContextfrom marimo._messaging.notebook.document import (NotebookCell,@@ -45,7 +46,11 @@ def _ctx(cells.extend(extra_doc_cells)doc = NotebookDocument(cells)with notebook_document_context(doc):- yield AsyncCodeModeContext(k)+ ctx = AsyncCodeModeContext(k)+ # Use a deterministic seed in tests for snapshot stability.+ ctx._id_generator = CellIdGenerator(seed=7)+ ctx._id_generator.seen_ids = set(doc.cell_ids)+ yield ctxdef _tx_ops(k: Kernel) -> list[dict[str, object]]:@@ -83,7 +88,7 @@ class TestAddCell:[{"type": "create-cell",- "cellId": "Hbol",+ "cellId": "qhHd","code": "x = 1","name": "","config": {@@ -94,7 +99,7 @@ class TestAddCell:"before": None,"after": None,},- {"type": "reorder-cells", "cellIds": ("Hbol",)},+ {"type": "reorder-cells", "cellIds": ("qhHd",)},])@@ -440,7 +445,7 @@ class TestSummary:nb.create_cell("x = 1", name="my_cell")captured = capsys.readouterr() # type: ignore[attr-defined]- assert captured.out == snapshot("created cell 'Hbol' (my_cell)\n")+ assert captured.out == snapshot("created cell 'qhHd' (my_cell)\n")async def test_edit_prints_summary(self, k: Kernel, capsys: object@@ -501,8 +506,8 @@ class TestSummary:captured = capsys.readouterr() # type: ignore[attr-defined]assert captured.out == snapshot("""\deleted cell '1'-created and ran cell 'Hbol' (new_cell)-created cell 'MJUe' (staged)+created and ran cell 'qhHd' (new_cell)+created cell 'BtdA' (staged)edited code of cell '0' and ranre-ran cell '2'""")@@ -691,3 +696,25 @@ class TestDocumentKernelDivergence:nb.run_cell("ghost")assert k.globals["z"] == 42++ async def test_create_cell_no_collision_with_doc_only_ids(+ self, k: Kernel+ ) -> None:+ """create_cell must not generate IDs that collide with cells+ that exist in the document but not in the kernel graph (B4)."""+ # Build a large set of document-only cells whose IDs come from+ # the same deterministic seed used by the test helper.+ gen = CellIdGenerator(seed=7)+ doc_only: list[NotebookCell] = []+ for _ in range(60):+ cid = gen.create_cell_id()+ doc_only.append(+ NotebookCell(id=cid, code="pass", name="", config=CellConfig())+ )++ with _ctx(k, extra_doc_cells=doc_only) as ctx:+ async with ctx as nb:+ # Should not raise ValueError from ID collision.+ new_id = nb.create_cell("x = 1")++ assert new_id not in {c.id for c in doc_only}diff --git a/tests/_convert/test_notebook_cell_ids.py b/tests/_convert/test_notebook_cell_ids.pyindex 24c70ad0a8..5c07e9daac 100644--- a/tests/_convert/test_notebook_cell_ids.py+++ b/tests/_convert/test_notebook_cell_ids.py@@ -15,7 +15,7 @@ def _kernel_cell_ids(source: str) -> list[str]:ir = parse_notebook(source)assert ir is not None- gen = CellIdGenerator()+ gen = CellIdGenerator(seed=42)ids = []for i, cell_def in enumerate(ir.cells):if isinstance(cell_def, SetupCell) or (