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: add cell ids to deserialize (#5166)
Myles Scolnickce93aa21aa26
diff --git a/frontend/src/core/cells/__tests__/ids.test.ts b/frontend/src/core/cells/__tests__/ids.test.tsindex f5d50534dd..09d929610e 100644--- a/frontend/src/core/cells/__tests__/ids.test.ts+++ b/frontend/src/core/cells/__tests__/ids.test.ts@@ -37,6 +37,16 @@ describe("HTMLCellId", () => {expect(cell).toBeDefined();expect(cell!.id.startsWith("cell-")).toBe(true);});++ it("create 1000 ids", () => {+ const ids: CellId[] = [];+ for (let i = 0; i < 1000; i++) {+ const id = CellId.create();+ ids.push(id);+ }+ expect(ids.length).toBe(1000);+ expect(new Set(ids).size).toBe(1000);+ });});describe("CellOutputId", () => {diff --git a/frontend/src/core/cells/ids.ts b/frontend/src/core/cells/ids.tsindex 1ebd74bf1d..9e0f3c607d 100644--- a/frontend/src/core/cells/ids.ts+++ b/frontend/src/core/cells/ids.ts@@ -7,6 +7,7 @@ import type { TypedString } from "../../utils/typed";const lowercase = "abcdefghijklmnopqrstuvwxyz";const uppercase = lowercase.toUpperCase();const alphabet = lowercase + uppercase;+const seen = new Set<CellId>();/*** A typed CellId@@ -17,11 +18,24 @@ export const CellId = {* Create a new CellId, a random 4 letter string.*/create(): CellId {- let id = "";- for (let i = 0; i < 4; i++) {- id += alphabet[Math.floor(Math.random() * alphabet.length)];+ let attempts = 0;+ let cellId: CellId;++ do {+ let id = "";+ for (let i = 0; i < 4; i++) {+ id += alphabet[Math.floor(Math.random() * alphabet.length)];+ }+ cellId = id as CellId;+ attempts++;+ } while (seen.has(cellId) && attempts < 100);++ if (attempts >= 100) {+ throw new Error("Failed to generate unique CellId after 100 attempts");}- return id as CellId;++ seen.add(cellId);+ return cellId;},};diff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.pyindex d59572cc26..b0157e21e7 100644--- a/marimo/_ast/cell_manager.py+++ b/marimo/_ast/cell_manager.py@@ -49,6 +49,34 @@ Obj: TypeAlias = "Cls | Fn[P, R]"LOGGER = _loggers.marimo_logger()+class CellIdGenerator:+ def __init__(self, prefix: str = "") -> None:+ self.prefix = prefix+ self.random_seed = random.Random(42)+ self.seen_ids: set[CellId_t] = set()++ def create_cell_id(self) -> CellId_t:+ """Create a new unique cell ID.++ Returns:+ CellId_t: A new cell ID consisting of the manager's prefix followed by 4 random letters.+ """+ attempts = 0+ while attempts < 100:+ # 4 random letters+ _id = self.prefix + "".join(+ self.random_seed.choices(string.ascii_letters, k=4)+ )+ if _id not in self.seen_ids:+ self.seen_ids.add(CellId_t(_id))+ return CellId_t(_id)+ attempts += 1++ raise ValueError(+ f"Failed to create a unique cell ID after {attempts} attempts"+ )++class CellManager:"""A manager for cells in a marimo notebook.@@ -62,7 +90,6 @@ class CellManager:Attributes:prefix (str): A prefix added to all cell IDs managed by this instanceunparsable (bool): Flag indicating if any unparsable cells were encountered- random_seed (random.Random): Seeded random number generator for deterministic cell ID creation"""def __init__(self, prefix: str = "") -> None:@@ -74,8 +101,7 @@ class CellManager:self._cell_data: dict[CellId_t, CellData] = {}self.prefix = prefixself.unparsable = False- self.random_seed = random.Random(42)- self.seen_ids: set[CellId_t] = set()+ self._cell_id_generator = CellIdGenerator(prefix)def create_cell_id(self) -> CellId_t:"""Create a new unique cell ID.@@ -83,16 +109,7 @@ class CellManager:Returns:CellId_t: A new cell ID consisting of the manager's prefix followed by 4 random letters."""- # 4 random letters- _id = self.prefix + "".join(- self.random_seed.choices(string.ascii_letters, k=4)- )- while _id in self.seen_ids:- _id = self.prefix + "".join(- self.random_seed.choices(string.ascii_letters, k=4)- )- self.seen_ids.add(CellId_t(_id))- return CellId_t(_id)+ return self._cell_id_generator.create_cell_id()def cell_decorator(self,@@ -475,7 +492,11 @@ class CellManager:# Add the new ids to the set, so we don't reuse them in the futurefor _id in sorted_ids:- self.seen_ids.add(_id)+ self._cell_id_generator.seen_ids.add(_id)++ @property+ def seen_ids(self) -> set[CellId_t]:+ return self._cell_id_generator.seen_idsdef _match_cell_ids_by_similarity(diff --git a/tests/_ast/test_cell_manager.py b/tests/_ast/test_cell_manager.pyindex 08c57e62f9..df6f167929 100644--- a/tests/_ast/test_cell_manager.py+++ b/tests/_ast/test_cell_manager.py@@ -448,3 +448,11 @@ def test_sort_cell_ids_by_similarity_more_cells():assert curr_manager.cell_data_at(CELL_B).code == "code2"assert curr_manager.cell_data_at(CELL_A).code == "code1"assert curr_manager.cell_data_at(CELL_X).code == "code3"+++def test_create_cell_id_1000():+ manager = CellManager()+ ids: set[CellId_t] = set()+ for _ in range(1000):+ ids.add(manager.create_cell_id())+ assert len(ids) == 1000