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: gracefully handle delete of unknown cell and read document on reconnect (#9033)
Myles Scolnick611afac87635
diff --git a/frontend/src/core/cells/__tests__/apply-transaction.test.ts b/frontend/src/core/cells/__tests__/apply-transaction.test.tsindex 34772d6f38..fd12d85129 100644--- a/frontend/src/core/cells/__tests__/apply-transaction.test.ts+++ b/frontend/src/core/cells/__tests__/apply-transaction.test.ts@@ -267,6 +267,34 @@ describe("applyTransactionChanges edge cases", () => {`);});+ it("delete-cell for nonexistent cell does not crash subsequent changes", () => {+ setup("a", "b", "c");+ const [, b] = state.cellIds.inOrderIds;+ // Simulate the scenario from the bug report: a delete-cell for a cell ID+ // that was never added to the frontend, followed by a create-cell and+ // a set-code update. The delete should be silently skipped, and the rest+ // of the transaction should still apply.+ apply([+ { type: "delete-cell", cellId: cellId("nonexistent") },+ {+ type: "create-cell",+ cellId: cellId("VrZA"),+ code: "import altair as alt",+ name: "",+ config: { hide_code: true },+ },+ { type: "set-code", cellId: b, code: "updated" },+ ]);+ expect(pretty(state)).toMatchInlineSnapshot(`+ "+ 0: 'a'+ 1: 'updated'+ 2: 'c'+ VrZA: 'import altair as alt' [hide_code]+ "+ `);+ });+it("empty changes is a no-op", () => {setup("a", "b");apply([]);diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex 07736244c9..059515185d 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -6,6 +6,7 @@ import { type Atom, atom, useAtom, useAtomValue } from "jotai";import { atomFamily, selectAtom, splitAtom } from "jotai/utils";import { createRef, type ReducerWithoutAction } from "react";import type { CellHandle } from "@/components/editor/notebook-cell";+import type { CollapsibleTree } from "@/utils/id-tree";import {type CellColumnId,type CellIndex,@@ -578,7 +579,18 @@ const {return state;}- const column = state.cellIds.findWithId(cellId);+ let column: CollapsibleTree<CellId>;+ try {+ column = state.cellIds.findWithId(cellId);+ } catch (error) {+ // Expected for kernel-only cells or out-of-order transactions.+ Logger.warn("Skipping delete for missing cellId", {+ cellId,+ error,+ });+ return state;+ }+const cellIndex = column.indexOfOrThrow(cellId);const focusIndex = cellIndex === 0 ? 1 : cellIndex - 1;let scrollKey: CellId | null = null;diff --git a/marimo/_server/api/endpoints/files.py b/marimo/_server/api/endpoints/files.pyindex c75dbbb1c5..5ab118da2a 100644--- a/marimo/_server/api/endpoints/files.py+++ b/marimo/_server/api/endpoints/files.py@@ -169,6 +169,14 @@ async def save(session = app_state.require_current_session()contents = session.app_file_manager.save(body)+ # Rebuild the document from the updated cell manager so that+ # reconnections (which read session.document) reflect the saved state.+ from marimo._session.session import _document_from_cell_manager++ session.document = _document_from_cell_manager(+ session.app_file_manager.app.cell_manager+ )+return PlainTextResponse(content=contents)diff --git a/marimo/_server/api/endpoints/ws/ws_kernel_ready.py b/marimo/_server/api/endpoints/ws/ws_kernel_ready.pyindex 409c1c6af1..7cda4f9bf0 100644--- a/marimo/_server/api/endpoints/ws/ws_kernel_ready.py+++ b/marimo/_server/api/endpoints/ws/ws_kernel_ready.py@@ -8,6 +8,7 @@ from typing import TYPE_CHECKINGfrom marimo import _loggersfrom marimo._ast.cell import CellConfigfrom marimo._dependencies.dependencies import DependencyManager+from marimo._messaging.notebook.document import NotebookDocumentfrom marimo._messaging.notification import (KernelCapabilitiesNotification,KernelReadyNotification,@@ -62,7 +63,8 @@ def build_kernel_ready(Returns:KernelReady message operation."""- codes, names, configs, cell_ids = _extract_cell_data(session, manager)+ document = session.document+ codes, names, configs, cell_ids = _extract_cell_data(document, manager)# Initialize RTC if neededif _should_init_rtc(rtc_enabled, mode):@@ -86,7 +88,7 @@ def build_kernel_ready(def _extract_cell_data(- session: Session,+ document: NotebookDocument,manager: SessionManager,) -> tuple[tuple[str, ...],@@ -97,14 +99,14 @@ def _extract_cell_data("""Extract cell data based on mode.Args:- session: Current session+ document: Current documentmanager: Session managerReturns:Tuple of (codes, names, configs, cell_ids)."""- file_manager = session.app_file_manager- app = file_manager.app+ if not document.cells:+ return ((), (), (), ())if manager.should_send_code_to_frontend():# Send full cell data to frontend@@ -112,12 +114,12 @@ def _extract_cell_data(zip(*tuple((- cell_data.code,- cell_data.name,- cell_data.config,- cell_data.cell_id,+ cell.code,+ cell.name,+ cell.config,+ cell.id,)- for cell_data in app.cell_manager.cell_data()+ for cell in document.cells)))@@ -127,8 +129,8 @@ def _extract_cell_data(codes, names, configs, cell_ids = tuple(zip(*tuple(- ("", cell_data.name, cell_data.config, cell_data.cell_id)- for cell_data in app.cell_manager.cell_data()+ ("", cell.name, cell.config, cell.id)+ for cell in document.cells)))diff --git a/tests/_server/api/endpoints/ws/test_ws_kernel_ready.py b/tests/_server/api/endpoints/ws/test_ws_kernel_ready.pynew file mode 100644index 0000000000..8ebceda304--- /dev/null+++ b/tests/_server/api/endpoints/ws/test_ws_kernel_ready.py@@ -0,0 +1,144 @@+# Copyright 2026 Marimo. All rights reserved.+"""Tests for _extract_cell_data reading from the NotebookDocument.++The key change under test: `_extract_cell_data` now reads from+``session.document`` (a ``NotebookDocument``) rather than directly from+``session.app_file_manager.app.cell_manager``. This means that+document-level mutations (applied via ``notebook-document-transaction``)+are reflected when a new client connects and receives ``kernel-ready``.+"""++from __future__ import annotations++from unittest.mock import MagicMock++from marimo._ast.cell import CellConfig+from marimo._messaging.notebook.changes import (+ CreateCell,+ DeleteCell,+ SetCode,+ Transaction,+)+from marimo._messaging.notebook.document import NotebookCell, NotebookDocument+from marimo._server.api.endpoints.ws.ws_kernel_ready import _extract_cell_data+from marimo._types.ids import CellId_t+++def _make_doc(*cells: tuple[str, str, str]) -> NotebookDocument:+ """Build a NotebookDocument from (id, code, name) triples."""+ return NotebookDocument(+ [+ NotebookCell(+ id=CellId_t(cid),+ code=code,+ name=name,+ config=CellConfig(),+ )+ for cid, code, name in cells+ ]+ )+++def _manager(send_code: bool) -> MagicMock:+ mgr = MagicMock()+ mgr.should_send_code_to_frontend.return_value = send_code+ return mgr+++class TestExtractCellDataFromDocument:+ """_extract_cell_data reads the document, not the cell_manager."""++ def test_empty_document(self) -> None:+ doc = NotebookDocument()+ result = _extract_cell_data(doc, _manager(send_code=True))+ assert result == ((), (), (), ())+ # Run mode should also handle empty document+ result = _extract_cell_data(doc, _manager(send_code=False))+ assert result == ((), (), (), ())++ def test_basic_extraction(self) -> None:+ doc = _make_doc(+ ("a", "x = 1", "setup"),+ ("b", "y = 2", "compute"),+ )+ codes, names, configs, cell_ids = _extract_cell_data(+ doc, _manager(send_code=True)+ )+ assert codes == ("x = 1", "y = 2")+ assert names == ("setup", "compute")+ assert cell_ids == (CellId_t("a"), CellId_t("b"))+ assert len(configs) == 2++ def test_hides_code_in_run_mode(self) -> None:+ doc = _make_doc(("a", "secret()", "fn"))+ codes, names, _, _ = _extract_cell_data(doc, _manager(send_code=False))+ assert codes == ("",)+ assert names == ("fn",)++ def test_document_mutations_reflected(self) -> None:+ """Mutations applied to the document are visible in _extract_cell_data.++ This is the core scenario: the kernel applies a transaction+ (e.g. from notebook-document-transaction) which mutates the+ document. A subsequent call to build_kernel_ready (during+ reconnection) should see the mutated state.+ """+ doc = _make_doc(+ ("a", "x = 1", "cell_a"),+ ("b", "y = 2", "cell_b"),+ ("c", "z = 3", "cell_c"),+ )++ # Simulate a transaction that deletes cell "b" and adds a new cell+ tx = Transaction(+ changes=(+ DeleteCell(cell_id=CellId_t("b")),+ CreateCell(+ cell_id=CellId_t("new"),+ code="import altair",+ name="chart",+ config=CellConfig(hide_code=True),+ ),+ ),+ source="kernel",+ )+ doc.apply(tx)++ codes, names, configs, cell_ids = _extract_cell_data(+ doc, _manager(send_code=True)+ )+ assert cell_ids == (+ CellId_t("a"),+ CellId_t("c"),+ CellId_t("new"),+ )+ assert codes == ("x = 1", "z = 3", "import altair")+ assert names == ("cell_a", "cell_c", "chart")+ # The new cell's config should be preserved+ assert configs[2].hide_code is True++ def test_set_code_transaction_reflected(self) -> None:+ """SetCode mutations are visible on reconnection."""+ doc = _make_doc(("a", "original", "cell_a"))+ tx = Transaction(+ changes=(SetCode(cell_id=CellId_t("a"), code="modified"),),+ source="kernel",+ )+ doc.apply(tx)++ codes, _, _, _ = _extract_cell_data(doc, _manager(send_code=True))+ assert codes == ("modified",)++ def test_set_code_hidden_in_run_mode(self) -> None:+ """Even after SetCode, run-mode still hides code."""+ doc = _make_doc(("a", "original", "cell_a"))+ doc.apply(+ Transaction(+ changes=(SetCode(cell_id=CellId_t("a"), code="modified"),),+ source="kernel",+ )+ )++ codes, names, _, _ = _extract_cell_data(doc, _manager(send_code=False))+ assert codes == ("",)+ assert names == ("cell_a",)