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.

fix: initialize cell_ids on notebook creation (#8310)

Julian Popescuec29b08a93e1
diff --git a/marimo/_convert/notebook.py b/marimo/_convert/notebook.py
index f200520be9..3b20fc9a06 100644
--- a/marimo/_convert/notebook.py
+++ b/marimo/_convert/notebook.py
@@ -1,6 +1,8 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+from marimo._ast.cell_id import CellIdGenerator
+from marimo._ast.names import SETUP_CELL_NAME
from marimo._schemas.notebook import (
NotebookCell,
NotebookCellConfig,
@@ -12,6 +14,7 @@ from marimo._schemas.serialization import (
CellDef,
NotebookSerialization,
NotebookSerializationV1,
+ SetupCell,
)
from marimo._utils.code import hash_code
from marimo._version import __version__
@@ -28,11 +31,18 @@ def convert_from_ir_to_notebook_v1(
Returns:
NotebookV1: The notebook v1.
"""
+ cell_id_generator = CellIdGenerator()
cells: list[NotebookCell] = []
- for data in notebook_ir.cells:
+ for i, data in enumerate(notebook_ir.cells):
+ if isinstance(data, SetupCell) or (
+ i == 0 and data.name == SETUP_CELL_NAME
+ ):
+ cell_id = SETUP_CELL_NAME
+ else:
+ cell_id = cell_id_generator.create_cell_id()
cells.append(
NotebookCell(
- id=None,
+ id=cell_id,
code=data.code,
code_hash=hash_code(data.code) if data.code else None,
name=data.name,
diff --git a/marimo/_pyodide/bootstrap.py b/marimo/_pyodide/bootstrap.py
index 7a301aaaf5..57f0771010 100644
--- a/marimo/_pyodide/bootstrap.py
+++ b/marimo/_pyodide/bootstrap.py
@@ -54,6 +54,7 @@ def instantiate(
session.put_control_request(
CreateNotebookCommand(
execution_requests=execution_requests,
+ cell_ids=tuple(app.cell_manager.cell_ids()),
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[], values=[], request=None
),
diff --git a/marimo/_runtime/commands.py b/marimo/_runtime/commands.py
index a5d3916ac8..e0243d7219 100644
--- a/marimo/_runtime/commands.py
+++ b/marimo/_runtime/commands.py
@@ -488,16 +488,16 @@ class CreateNotebookCommand(Command):
Attributes:
execution_requests: ExecuteCellCommand for each notebook cell.
- cell_ids: Initial cell IDs in the notebook (unused for now).
+ cell_ids: Initial cell IDs in the notebook.
set_ui_element_value_request: Initial UI element values.
auto_run: Whether to automatically execute cells on instantiation.
request: HTTP request context if available.
"""
execution_requests: tuple[ExecuteCellCommand, ...]
+ cell_ids: tuple[CellId_t, ...]
set_ui_element_value_request: UpdateUIElementCommand
auto_run: bool
- cell_ids: Optional[tuple[CellId_t, ...]] = None
request: Optional[HTTPRequest] = None
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 5809883c8f..7be8933b03 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -72,6 +72,7 @@ from marimo._messaging.notification import (
SQLTablePreviewNotification,
StorageDownloadReadyNotification,
StorageEntriesNotification,
+ UpdateCellIdsNotification,
ValidateSQLResultNotification,
VariableDeclarationNotification,
VariablesNotification,
@@ -2103,6 +2104,10 @@ class Kernel:
LOGGER.info("App is already instantiated, skipping instantiation.")
return
+ broadcast_notification(
+ UpdateCellIdsNotification(cell_ids=list(request.cell_ids))
+ )
+
# Handle markdown cells specially during kernel-ready initialization
execution_requests = {
er.cell_id: er for er in request.execution_requests
diff --git a/marimo/_session/session.py b/marimo/_session/session.py
index a733b0af95..70d17b24f4 100644
--- a/marimo/_session/session.py
+++ b/marimo/_session/session.py
@@ -371,13 +371,12 @@ class SessionImpl(Session):
http_request: Optional[HTTPRequest],
) -> None:
"""Instantiate the app."""
+ app = self.app_file_manager.app
# If codes are provided, use them instead of the file codes
# This is used when the frontend has local edits that should be
# used instead of the stored file (e.g. local editing before connecting).
- codes = (
- request.codes or self.app_file_manager.app.cell_manager.code_map()
- )
+ codes = request.codes or app.cell_manager.code_map()
execution_requests = tuple(
ExecuteCellCommand(
@@ -391,6 +390,7 @@ class SessionImpl(Session):
self.put_control_request(
CreateNotebookCommand(
execution_requests=execution_requests,
+ cell_ids=tuple(app.cell_manager.cell_ids()),
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=request.object_ids,
values=request.values,
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index 650dcbf626..8bb0412a18 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -826,20 +826,16 @@ components:
description: "Instantiate and initialize a notebook.\n\n Sent when a notebook\
\ is first loaded. Contains all cells and initial UI element values.\n\n \
\ Attributes:\n execution_requests: ExecuteCellCommand for each notebook\
- \ cell.\n cell_ids: Initial cell IDs in the notebook (unused for now).\n\
- \ set_ui_element_value_request: Initial UI element values.\n \
- \ auto_run: Whether to automatically execute cells on instantiation.\n \
- \ request: HTTP request context if available."
+ \ cell.\n cell_ids: Initial cell IDs in the notebook.\n set_ui_element_value_request:\
+ \ Initial UI element values.\n auto_run: Whether to automatically execute\
+ \ cells on instantiation.\n request: HTTP request context if available."
properties:
autoRun:
type: boolean
cellIds:
- anyOf:
- - items:
- type: string
- type: array
- - type: 'null'
- default: null
+ items:
+ type: string
+ type: array
executionRequests:
items:
$ref: '#/components/schemas/ExecuteCellCommand'
@@ -857,6 +853,7 @@ components:
required:
- type
- executionRequests
+ - cellIds
- setUiElementValueRequest
- autoRun
title: CreateNotebookCommand
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 42fdc30d37..8c088e89bb 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -3703,15 +3703,14 @@ export interface components {
*
* Attributes:
* execution_requests: ExecuteCellCommand for each notebook cell.
- * cell_ids: Initial cell IDs in the notebook (unused for now).
+ * cell_ids: Initial cell IDs in the notebook.
* set_ui_element_value_request: Initial UI element values.
* auto_run: Whether to automatically execute cells on instantiation.
* request: HTTP request context if available.
*/
CreateNotebookCommand: {
autoRun: boolean;
- /** @default null */
- cellIds?: string[] | null;
+ cellIds: string[];
executionRequests: components["schemas"]["ExecuteCellCommand"][];
/** @default null */
request?: components["schemas"]["HTTPRequest"] | null;
diff --git a/tests/_convert/test_notebook_cell_ids.py b/tests/_convert/test_notebook_cell_ids.py
new file mode 100644
index 0000000000..24c70ad0a8
--- /dev/null
+++ b/tests/_convert/test_notebook_cell_ids.py
@@ -0,0 +1,133 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from textwrap import dedent
+
+from marimo._ast.cell_id import CellIdGenerator
+from marimo._ast.names import SETUP_CELL_NAME
+from marimo._convert.converters import MarimoConvert
+
+
+def _kernel_cell_ids(source: str) -> list[str]:
+ """Simulate the cell IDs the kernel would generate for a notebook."""
+ from marimo._ast.parse import parse_notebook
+ from marimo._schemas.serialization import SetupCell
+
+ ir = parse_notebook(source)
+ assert ir is not None
+ gen = CellIdGenerator()
+ ids = []
+ for i, cell_def in enumerate(ir.cells):
+ if isinstance(cell_def, SetupCell) or (
+ i == 0 and cell_def.name == SETUP_CELL_NAME
+ ):
+ ids.append(SETUP_CELL_NAME)
+ else:
+ ids.append(gen.create_cell_id())
+ return ids
+
+
+def test_snapshot_ids_match_kernel_ids():
+ source = dedent(
+ """
+ import marimo
+
+ __generated_with = "0.1.0"
+ app = marimo.App()
+
+ @app.cell
+ def hello():
+ x = 1
+ return (x,)
+
+ @app.cell
+ def world(x):
+ y = x + 1
+ return (y,)
+
+ if __name__ == "__main__":
+ app.run()
+ """
+ ).strip()
+
+ notebook = MarimoConvert.from_py(source).to_notebook_v1()
+ snapshot_ids = [c["id"] for c in notebook["cells"]]
+ kernel_ids = _kernel_cell_ids(source)
+
+ assert snapshot_ids == kernel_ids
+ assert all(snapshot_id is not None for snapshot_id in snapshot_ids)
+
+
+def test_snapshot_ids_match_kernel_ids_with_setup_cell():
+ source = dedent(
+ """
+ import marimo
+
+ __generated_with = "0.1.0"
+ app = marimo.App()
+
+ with app.setup:
+ import numpy as np
+
+ @app.cell
+ def hello():
+ x = 1
+ return (x,)
+
+ @app.cell
+ def world(x):
+ y = x + 1
+ return (y,)
+
+ if __name__ == "__main__":
+ app.run()
+ """
+ ).strip()
+
+ notebook = MarimoConvert.from_py(source).to_notebook_v1()
+ snapshot_ids = [c["id"] for c in notebook["cells"]]
+ kernel_ids = _kernel_cell_ids(source)
+
+ assert snapshot_ids == kernel_ids
+ assert snapshot_ids[0] == SETUP_CELL_NAME
+
+
+def test_snapshot_ids_are_deterministic():
+ source = dedent(
+ """
+ import marimo
+
+ __generated_with = "0.1.0"
+ app = marimo.App()
+
+ @app.cell
+ def _():
+ x = 1
+ return (x,)
+
+ @app.cell
+ def _():
+ y = 2
+ return (y,)
+
+ @app.cell
+ def _():
+ z = 3
+ return (z,)
+
+ if __name__ == "__main__":
+ app.run()
+ """
+ ).strip()
+
+ ids_1 = [
+ c["id"]
+ for c in MarimoConvert.from_py(source).to_notebook_v1()["cells"]
+ ]
+ ids_2 = [
+ c["id"]
+ for c in MarimoConvert.from_py(source).to_notebook_v1()["cells"]
+ ]
+
+ assert ids_1 == ids_2
+ assert len(set(ids_1)) == 3 # all unique
diff --git a/tests/_pyodide/test_pyodide_session.py b/tests/_pyodide/test_pyodide_session.py
index 7093564c9a..4d0440d255 100644
--- a/tests/_pyodide/test_pyodide_session.py
+++ b/tests/_pyodide/test_pyodide_session.py
@@ -352,7 +352,7 @@ async def test_pyodide_session_put_input(
# Notebook operations
(
'{"type": "create-notebook", "executionRequests": [{"cellId": "cell-1", "code": "print(1)", "type": "execute-cell"}], '
- '"setUiElementValueRequest": {"objectIds": [], "values": [], "type": "update-ui-element"}, '
+ '"cellIds": ["cell-1"], "setUiElementValueRequest": {"objectIds": [], "values": [], "type": "update-ui-element"}, '
'"autoRun": true}',
CreateNotebookCommand,
),
diff --git a/tests/_runtime/test_dotenv.py b/tests/_runtime/test_dotenv.py
index cf4bae0e3e..530713622f 100644
--- a/tests/_runtime/test_dotenv.py
+++ b/tests/_runtime/test_dotenv.py
@@ -84,6 +84,7 @@ async def test_load_dotenv_on_instantiate(mocked_kernel: MockedKernel):
# Create a CreationRequest
request = CreateNotebookCommand(
execution_requests=(),
+ cell_ids=(),
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
values=[],
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 6c3178cf4d..76387d0dd5 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -344,6 +344,7 @@ class TestExecution:
cell_id="1", code="s = mo.ui.slider(0, 10, value=1)"
),
),
+ cell_ids=("0", "1"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[(id_provider.take_id(), 2)]
),
@@ -361,6 +362,7 @@ class TestExecution:
er1 := ExecuteCellCommand(cell_id="1", code="y=x+1"),
er2 := ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
+ cell_ids=("0", "1", "2"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
@@ -396,6 +398,7 @@ class TestExecution:
ExecuteCellCommand(cell_id="1", code="y=x+1"),
ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
+ cell_ids=("0", "1", "2"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
@@ -423,6 +426,7 @@ class TestExecution:
er2 := ExecuteCellCommand(cell_id="1", code="y=x+1"),
er3 := ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
+ cell_ids=("0", "1", "2"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
@@ -451,6 +455,7 @@ class TestExecution:
ExecuteCellCommand(cell_id="1", code="y=x+1"),
ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
+ cell_ids=("0", "1", "2"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
@@ -493,6 +498,7 @@ class TestExecution:
ExecuteCellCommand(cell_id="1", code="y=x+1"),
ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
+ cell_ids=("0", "1", "2"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
@@ -521,6 +527,7 @@ class TestExecution:
er1 := ExecuteCellCommand(cell_id="1", code="y=x+1"),
er2 := ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
+ cell_ids=("0", "1", "2"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
@@ -556,6 +563,7 @@ class TestExecution:
ExecuteCellCommand(cell_id="2", code=" \n "),
ExecuteCellCommand(cell_id="3", code="y=x+1"),
),
+ cell_ids=("0", "1", "2", "3"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
@@ -1895,6 +1903,7 @@ except NameError:
ExecuteCellCommand(cell_id="1", code="y = 1"),
ExecuteCellCommand(cell_id="2", code="z = 2"),
),
+ cell_ids=("0", "1", "2"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
@@ -3699,6 +3708,7 @@ class TestMarkdownHandling:
# Create a creation request with auto_run=False to trigger the markdown handling
creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
+ cell_ids=tuple(cell.cell_id for cell in execution_requests),
auto_run=False,
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
@@ -3796,6 +3806,7 @@ class TestMarkdownHandling:
creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
+ cell_ids=tuple(cell.cell_id for cell in execution_requests),
auto_run=False,
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
@@ -3836,6 +3847,7 @@ class TestMarkdownHandling:
creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
+ cell_ids=tuple(cell.cell_id for cell in execution_requests),
auto_run=False,
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
@@ -3867,6 +3879,7 @@ class TestMarkdownHandling:
creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
+ cell_ids=tuple(cell.cell_id for cell in execution_requests),
auto_run=False,
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
@@ -3926,6 +3939,7 @@ class TestMarkdownHandling:
creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
+ cell_ids=tuple(cell.cell_id for cell in execution_requests),
auto_run=False,
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
@@ -3984,6 +3998,7 @@ class TestMarkdownHandling:
creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
+ cell_ids=tuple(cell.cell_id for cell in execution_requests),
auto_run=False,
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index b771befc48..65f4f27f92 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -360,7 +360,7 @@ async def test_connects_to_existing_session_with_same_file(
# This can/may change if implementation changes, but this is a snapshot to
# make sure it doesn't change when we don't expect it to
assert len(messages1) == 14
- assert messages1[0]["op"] == "variables"
+ assert messages1[0]["op"] == "update-cell-ids"
# Connect second client - should connect to same session
with client.websocket_connect(ws_2) as websocket2:
@@ -377,7 +377,7 @@ async def test_connects_to_existing_session_with_same_file(
# This can/may change if implementation changes, but this is a snapshot to
# make sure it doesn't change when we don't expect it to
assert len(messages2) == 4
- assert messages2[0]["op"] == "variables"
+ assert messages2[0]["op"] == "update-cell-ids"
def flush_messages(
diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.py
index 9fa98f4549..eab462d8dd 100644
--- a/tests/_server/test_sessions.py
+++ b/tests/_server/test_sessions.py
@@ -245,6 +245,7 @@ def test_kernel_manager_interrupt(tmp_path: Path) -> None:
),
),
),
+ cell_ids=("1",),
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[], values=[]
),
diff --git a/tests/_session/state/test_session_view.py b/tests/_session/state/test_session_view.py
index aceade28c8..6ef7a7e359 100644
--- a/tests/_session/state/test_session_view.py
+++ b/tests/_session/state/test_session_view.py
@@ -180,6 +180,7 @@ def test_ui_values(session_view: SessionView) -> None:
session_view.add_control_request(
CreateNotebookCommand(
execution_requests=(),
+ cell_ids=(),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[("test_ui3", 101112)]
),
@@ -501,6 +502,7 @@ def test_last_run_code(session_view: SessionView) -> None:
execution_requests=(
ExecuteCellCommand(cell_id=cell_id, code="print('hello')"),
),
+ cell_ids=(cell_id, "cell_2"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),