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
chore: create cell ids on the backend, and change to random alpha (#663)
Myles Scolnick96f74ec22b55
diff --git a/.github/workflows/playwright.yml b/.github/workflows/playwright.ymlindex 79271887cd..60af15e75a 100644--- a/.github/workflows/playwright.yml+++ b/.github/workflows/playwright.yml@@ -7,7 +7,7 @@ on:jobs:test:- timeout-minutes: 10+ timeout-minutes: 16runs-on: ubuntu-latestdefaults:run:diff --git a/frontend/e2e-tests/components.spec.ts b/frontend/e2e-tests/components.spec.tsindex 39a7f71452..7ae2d7cca9 100644--- a/frontend/e2e-tests/components.spec.ts+++ b/frontend/e2e-tests/components.spec.ts@@ -13,15 +13,18 @@ test.beforeEach(async ({ page }, info) => {const pageHelper = (page: Page) => {return {- selectBasicComponent: async (type: string) => {- const select = await page.locator("#cell-1").locator("select");+ cell(index: number) {+ return page.locator(".Cell").nth(index);+ },+ async selectBasicComponent(type: string) {+ const select = await this.cell(1).locator("select");await select.selectOption({ label: type });},- selectComplexComponent: async (type: string) => {- const select = await page.locator("#cell-4").locator("select");+ async selectComplexComponent(type: string) {+ const select = await this.cell(4).locator("select");await select.selectOption({ label: type });},- verifyOutput: async (text: string) => {+ async verifyOutput(text: string) {await expect(page.getByText(`The element's current value is ${text}`)).toBeVisible();@@ -96,7 +99,7 @@ test("date", async ({ page }) => {test("dropdown", async ({ page }) => {const helper = pageHelper(page);await helper.selectBasicComponent("dropdown");- const element = page.locator("#cell-2").getByRole("combobox");+ const element = helper.cell(2).getByRole("combobox");// Verify is visibleawait expect(element).toBeVisible();@@ -243,7 +246,7 @@ test("table", async ({ page }) => {// Click first checkbox to select allawait page.getByRole("checkbox").first().click();await expect(- page.locator("#cell-3").locator(".marimo-json-output").first()+ helper.cell(3).locator(".marimo-json-output").first()).toHaveText(`[2 Items@@ -263,7 +266,7 @@ test("table", async ({ page }) => {// Click second checkbox to remove first rowawait page.getByRole("checkbox").nth(1).click();await expect(- page.locator("#cell-3").locator(".marimo-json-output").first()+ helper.cell(3).locator(".marimo-json-output").first()).toHaveText(`[1 Items@@ -327,7 +330,7 @@ test("complex - array", async ({ page }) => {await date.fill("2020-01-20");// Verify outputawait expect(- page.locator("#cell-6").locator(".marimo-json-output").first()+ helper.cell(6).locator(".marimo-json-output").first()).toHaveText(`[3 Items@@ -357,7 +360,7 @@ test("complex - batch", async ({ page }) => {await date.fill("2020-04-20");// Verify outputawait expect(- page.locator("#cell-6").locator(".marimo-json-output").first()+ helper.cell(6).locator(".marimo-json-output").first()).toHaveText(`{2 Items@@ -390,7 +393,7 @@ test("complex - dictionary", async ({ page }) => {await buttons.last().click();// Verify outputawait expect(- page.locator("#cell-6").locator(".marimo-json-output").first()+ helper.cell(6).locator(".marimo-json-output").first()).toHaveText(`{3 Itemsdiff --git a/frontend/src/components/dependency-graph/custom-node.tsx b/frontend/src/components/dependency-graph/custom-node.tsxindex 708fc73be7..73fd6f1468 100644--- a/frontend/src/components/dependency-graph/custom-node.tsx+++ b/frontend/src/components/dependency-graph/custom-node.tsx@@ -7,6 +7,7 @@ import { Handle, Position, useStore } from "reactflow";import { CustomNodeProps, getNodeHeight } from "./elements";import { displayCellName } from "@/core/cells/names";import { CellId } from "@/core/cells/ids";+import { useCellIds } from "@/core/cells/cells";function getWidth(canvasWidth: number) {const minWidth = 100;@@ -18,6 +19,7 @@ function getWidth(canvasWidth: number) {export const CustomNode = memo((props: CustomNodeProps) => {const { data, selected, id } = props;const cell = useAtomValue(data.atom);+ const cellIndex = useCellIds().indexOf(id as CellId);const nonSelectedColor = "var(--gray-3)";const selectedColor = "var(--gray-9)";const color = selected ? selectedColor : nonSelectedColor;@@ -49,7 +51,7 @@ export const CustomNode = memo((props: CustomNodeProps) => {}}><div className="text-muted-foreground font-semibold text-xs py-1 px-2 bg-muted border-b">- {displayCellName(cell.name, id as CellId)}+ {displayCellName(cell.name, cellIndex)}</div><TinyCode code={cell.code} /></div>diff --git a/frontend/src/components/editor/chrome/panels/logs-panel.tsx b/frontend/src/components/editor/chrome/panels/logs-panel.tsxindex 8d9fcc2d07..06ef08ce3a 100644--- a/frontend/src/components/editor/chrome/panels/logs-panel.tsx+++ b/frontend/src/components/editor/chrome/panels/logs-panel.tsx@@ -4,6 +4,7 @@ import { CellLog, formatLogTimestamp } from "@/core/cells/logs";import { cn } from "@/utils/cn";import React from "react";import { FileTextIcon } from "lucide-react";+import { CellLink } from "../../links/cell-link";interface Props {className?: string;@@ -77,7 +78,7 @@ function formatLog(log: CellLog) {<span className="flex-shrink-0 text-[var(--gray-10)]">[{timestamp}]</span><span className={cn("flex-shrink-0", color)}>{level}</span><span className="flex-shrink-0 text-[var(--gray-10)]">- ({log.cellId})+ (<CellLink cellId={log.cellId} />)</span>{log.message}</>diff --git a/frontend/src/components/editor/links/cell-link.tsx b/frontend/src/components/editor/links/cell-link.tsxindex 4b7cf25222..165b2bae4a 100644--- a/frontend/src/components/editor/links/cell-link.tsx+++ b/frontend/src/components/editor/links/cell-link.tsx@@ -3,7 +3,7 @@ import { CellId, HTMLCellId } from "@/core/cells/ids";import { Logger } from "../../../utils/Logger";import { cn } from "@/utils/cn";import { displayCellName } from "@/core/cells/names";-import { useCellNames } from "@/core/cells/cells";+import { useCellIds, useCellNames } from "@/core/cells/cells";interface Props {cellId: CellId;@@ -15,6 +15,7 @@ interface Props {export const CellLink = (props: Props): JSX.Element => {const { className, cellId, variant } = props;const cellName = useCellNames()[cellId] ?? "";+ const cellIndex = useCellIds().indexOf(cellId);const cellHtmlId = HTMLCellId.create(cellId);return (@@ -49,7 +50,7 @@ export const CellLink = (props: Props): JSX.Element => {}}}>- {displayCellName(cellName, cellId)}+ {displayCellName(cellName, cellIndex)}</div>);};diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.tsindex 8926ff4832..0cc173b119 100644--- a/frontend/src/core/cells/__tests__/cells.test.ts+++ b/frontend/src/core/cells/__tests__/cells.test.ts@@ -1,5 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */-import { beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import {NotebookState,exportedForTesting,@@ -28,14 +28,27 @@ describe("cell reducer", () => {cells = flattenNotebookCells(state);});+ let i = 0;+ const originalCreate = CellId.create.bind(CellId);++ beforeAll(() => {+ CellId.create = () => {+ return `${i++}` as CellId;+ };+ });+beforeEach(() => {- CellId.reset();+ i = 0;state = initialNotebookState();actions.createNewCell({ cellId: undefined!, before: false });firstCellId = state.cellIds[0];});+ afterAll(() => {+ CellId.create = originalCreate;+ });+it("can add a cell after another cell", () => {actions.createNewCell({cellId: firstCellId,diff --git a/frontend/src/core/cells/__tests__/names.test.ts b/frontend/src/core/cells/__tests__/names.test.tsindex 1a716dc21a..65cbdbea05 100644--- a/frontend/src/core/cells/__tests__/names.test.ts+++ b/frontend/src/core/cells/__tests__/names.test.ts@@ -1,6 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */-import { CellId } from "../ids";import {normalizeName,DEFAULT_CELL_NAME,@@ -46,12 +45,12 @@ describe("getValidName", () => {});describe("displayCellName", () => {- const fallbackCellId = "1" as CellId;it("should return the name if it is not the default cell name", () => {- expect(displayCellName("custom_name", fallbackCellId)).toBe("custom_name");+ expect(displayCellName("custom_name", 1)).toBe("custom_name");});it("should return the HTML cell ID if the name is the default cell name", () => {- expect(displayCellName(DEFAULT_CELL_NAME, fallbackCellId)).toBe("cell-1");+ expect(displayCellName(DEFAULT_CELL_NAME, 0)).toBe("cell-0");+ expect(displayCellName(DEFAULT_CELL_NAME, 1)).toBe("cell-1");});});diff --git a/frontend/src/core/cells/ids.ts b/frontend/src/core/cells/ids.tsindex e6efcada96..42426541bf 100644--- a/frontend/src/core/cells/ids.ts+++ b/frontend/src/core/cells/ids.ts@@ -4,25 +4,24 @@import { invariant } from "@/utils/invariant";import { TypedString } from "../../utils/typed";+const lowercase = "abcdefghijklmnopqrstuvwxyz";+const uppercase = lowercase.toUpperCase();+const alphabet = lowercase + uppercase;+/*** A typed CellId*/export type CellId = TypedString<"CellId">;-let counter = 0;export const CellId = {/**- * Create a new CellId+ * Create a new CellId, a random 4 letter string.*/create(): CellId {- const next = counter++;- return next.toString() as CellId;- },-- /**- * Reset id provider.- */- reset() {- counter = 0;+ let id = "";+ for (let i = 0; i < 4; i++) {+ id += alphabet[Math.floor(Math.random() * alphabet.length)];+ }+ return id as CellId;},};diff --git a/frontend/src/core/cells/names.ts b/frontend/src/core/cells/names.tsindex a132f49a98..9b4d63ccbf 100644--- a/frontend/src/core/cells/names.ts+++ b/frontend/src/core/cells/names.ts@@ -1,7 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */-import { CellId, HTMLCellId } from "./ids";-export const DEFAULT_CELL_NAME = "__";// Generated with `python scripts/print_banned_cell_names.py`@@ -90,9 +88,9 @@ export function getValidName(name: string, existingNames: string[]): string {/*** Print the cell name if differs from DEFAULT_CELL_NAME*/-export function displayCellName(name: string, fallbackCellId: CellId): string {+export function displayCellName(name: string, cellIndex: number): string {if (name !== DEFAULT_CELL_NAME) {return name;}- return HTMLCellId.create(fallbackCellId);+ return `cell-${cellIndex}`;}diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.tsindex d71122ae51..0c4f346322 100644--- a/frontend/src/core/kernel/messages.ts+++ b/frontend/src/core/kernel/messages.ts@@ -169,6 +169,10 @@ export type OperationMessage =* The cell codes. Will be empty in Read mode.*/codes: string[];+ /**+ * The cell IDs+ */+ cell_ids: CellId[];/*** The layout of the notebook* May be undefined if there is no layout set.diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex 28736fa715..9d87f3e273 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -10,7 +10,6 @@ import { AUTOCOMPLETER } from "@/core/codemirror/completion/Autocompleter";import { UI_ELEMENT_REGISTRY } from "@/core/dom/uiregistry";import { OperationMessage } from "@/core/kernel/messages";import { sendInstantiate } from "../network/requests";-import { CellId } from "../cells/ids";import { CellData } from "../cells/types";import { createCell } from "../cells/types";import { useErrorBoundary } from "react-error-boundary";@@ -52,16 +51,12 @@ export function useMarimoWebSocket(opts: {const msg = jsonParseWithSpecialChar<OperationMessage>(e.data);switch (msg.op) {case "kernel-ready": {- const { codes, names, layout, configs } = msg.data;-- // TODO(akshayka): Get rid of this once the kernel sends cell IDs in- // kernel-ready.- CellId.reset();+ const { codes, names, layout, configs, cell_ids } = msg.data;// Set the layout, initial codes, cellsconst cells = codes.map((code, i) =>createCell({- id: CellId.create(),+ id: cell_ids[i],code,edited: !autoInstantiate,name: names[i],diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex 726728dd2a..5aa23808f5 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -1,6 +1,8 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import random+import stringfrom collections.abc import Sequencefrom dataclasses import asdict, dataclassfrom typing import (@@ -232,13 +234,12 @@ class CellManager:def __init__(self) -> None:self._cell_data: dict[CellId_t, CellData] = {}self._cell_data = OrderedDict()- self._cell_id_counter = 0self.unparsable = False+ self.random_seed = random.Random(42)def create_cell_id(self) -> CellId_t:- cell_id = str(self._cell_id_counter)- self._cell_id_counter += 1- return cell_id+ # 4 random letters+ return "".join(self.random_seed.choices(string.ascii_letters, k=4))def cell_decorator(self,@@ -259,7 +260,7 @@ class CellManager:func: CellFuncTypeBound,) -> CellFunction[CellFuncTypeBound]:cell_function = cell_factory(- func, cell_id=str(self._cell_id_counter)+ func, cell_id=self.create_cell_id())cell_function.cell.configure(cell_config)self._register_cell_function(cell_function)@@ -272,7 +273,7 @@ class CellManager:# If the decorator was used without parentheses, func will be the# decorated function- cell_function = cell_factory(func, cell_id=str(self._cell_id_counter))+ cell_function = cell_factory(func, cell_id=self.create_cell_id())cell_function.cell.configure(cell_config)self._register_cell_function(cell_function)return cell_function@@ -281,6 +282,7 @@ class CellManager:self, cell_function: CellFunction[CellFuncTypeBound]) -> None:self.register_cell(+ cell_id=cell_function.cell.cell_id,code=cell_function.cell.code,name=cell_function.__name__,config=cell_function.cell.config,@@ -289,12 +291,15 @@ class CellManager:def register_cell(self,+ cell_id: Optional[CellId_t],code: str,config: Optional[CellConfig],name: str = "__",cell_function: Optional[CellFunction[CellFuncType]] = None,) -> None:- cell_id = self.create_cell_id()+ if cell_id is None:+ cell_id = self.create_cell_id()+self._cell_data[cell_id] = CellData(cell_id=cell_id,code=code,@@ -319,9 +324,10 @@ class CellManager:)self.register_cell(- code,- cell_config,- name or "__",+ cell_id=self.create_cell_id(),+ code=code,+ config=cell_config,+ name=name or "__",cell_function=None,)diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex 61065ca830..d842648b8c 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -85,7 +85,7 @@ class Cell:body: Optional[CodeType]last_expr: Optional[CodeType]# unique id- cell_id: Optional[CellId_t]+ cell_id: CellId_t# Mutable fields# config: explicit configuration of celldiff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.pyindex d3d602cb00..30c4591340 100644--- a/marimo/_ast/compiler.py+++ b/marimo/_ast/compiler.py@@ -68,7 +68,7 @@ def compile_cell(code: str, cell_id: CellId_t) -> Cell:cell_id=cell_id,)- v = ScopedVisitor("cell_" + str(cell_id) if cell_id is not None else None)+ v = ScopedVisitor("cell_" + cell_id)v.visit(module)expr: Union[ast.Expression, str]diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex 9fb2a4d898..48ec315fed 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -249,6 +249,7 @@ class KernelReady(Op):"""Kernel is ready for execution."""name: ClassVar[str] = "kernel-ready"+ cell_ids: tuple[CellId_t, ...]codes: tuple[str, ...]names: tuple[str, ...]layout: Optional[LayoutConfig]diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.pyindex 382b4d14b8..f4bf5c0e67 100644--- a/marimo/_server/api/endpoints/ws.py+++ b/marimo/_server/api/endpoints/ws.py@@ -87,20 +87,25 @@ class WebsocketHandler(SessionHandler):app = mgr.load_app()layout: Optional[LayoutConfig] = Noneif mgr.should_send_code_to_frontend():- codes, names, configs = tuple(+ codes, names, configs, cell_ids = tuple(zip(*tuple(- (cell_data.code, cell_data.name, cell_data.config)+ (+ cell_data.code,+ cell_data.name,+ cell_data.config,+ cell_data.cell_id,+ )for cell_data in app.cell_manager.cell_data())))else:- codes, names, configs = tuple(+ codes, names, configs, cell_ids = tuple(zip(*tuple(# Don't send code to frontend in run mode- ("", "", cell_data.config)+ ("", "", cell_data.config, cell_data.cell_id)for cell_data in app.cell_manager.cell_data()))@@ -123,6 +128,7 @@ class WebsocketHandler(SessionHandler):names=names,configs=configs,layout=layout,+ cell_ids=cell_ids,)),)diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 7657532969..7f51041ff9 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -281,8 +281,8 @@ class SessionManager:self.app_config: _AppConfigself.include_code = include_code- app = self.load_app()- self.app_config = app.config+ self.app = self.load_app()+ self.app_config = self.app.configif mode == SessionMode.EDIT:# In edit mode, the server gets a random token to prevent@@ -292,9 +292,8 @@ class SessionManager:else:# Because run-mode is read-only, all that matters is that# the frontend's app matches the server's app.- assert app is not Noneself.server_token = str(- hash("".join(code for code in app.cell_manager.codes()))+ hash("".join(code for code in self.app.cell_manager.codes())))def load_app(self) -> InternalApp:@@ -302,15 +301,16 @@ class SessionManager:Load the app from the current file.Otherwise, return an empty app."""-app = codegen.get_app(self.filename)if app is None:empty_app = InternalApp(App())empty_app.cell_manager.register_cell(+ cell_id=None,code="",config=CellConfig(),)return empty_app+return InternalApp(app)def update_app_config(self, config: dict[str, Any]) -> None:diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.pyindex 9ab0f555e2..88ccb88e67 100644--- a/tests/_server/api/endpoints/test_ws.py+++ b/tests/_server/api/endpoints/test_ws.py@@ -1,19 +1,35 @@# Copyright 2024 Marimo. All rights reserved.+import json+import pytestfrom starlette.testclient import TestClientfrom starlette.websockets import WebSocketDisconnect-KERNEL_READY_RESPONSE = '{"op": "kernel-ready", "data": {"codes": ["import marimo as mo"], "names": ["__"], "layout": null, "configs": [{"disabled": false, "hide_code": false}]}}' # noqa: E501+KERNEL_READY_RESPONSE = {+ "codes": ["import marimo as mo"],+ "names": ["__"],+ "layout": None,+ "configs": [{"disabled": False, "hide_code": False}],+}HEADERS = {"Marimo-Server-Token": "fake-token",}+def assert_kernel_ready_response(data_str: str) -> None:+ as_json = json.loads(data_str)+ data = as_json["data"]+ assert data["cell_ids"]+ assert len(data["cell_ids"]) == 1+ del data["cell_ids"]+ assert data == KERNEL_READY_RESPONSE++def test_ws(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=123") as websocket:data = websocket.receive_text()- assert data == KERNEL_READY_RESPONSE+ assert_kernel_ready_response(data)# shut down after websocket context manager exists, otherwise# the test fails on windows (event loop closed twice)client.post("/api/kernel/shutdown", headers=HEADERS)@@ -30,17 +46,17 @@ def test_without_session(client: TestClient) -> None:def test_refresh(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=123") as websocket:data = websocket.receive_text()- assert data == KERNEL_READY_RESPONSE+ assert_kernel_ready_response(data)# New session with new ID (simulates refresh)with client.websocket_connect("/ws?session_id=455") as websocket:data = websocket.receive_text()- assert data == KERNEL_READY_RESPONSE+ assert_kernel_ready_response(data)def test_disconnect_and_reconnect(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=123") as websocket:data = websocket.receive_text()- assert data == KERNEL_READY_RESPONSE+ assert_kernel_ready_response(data)websocket.close()# Connect by the same session idwith client.websocket_connect("/ws?session_id=123") as websocket:@@ -52,7 +68,7 @@ def test_disconnect_and_reconnect(client: TestClient) -> None:def test_disconnect_then_reconnect_then_refresh(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=123") as websocket:data = websocket.receive_text()- assert data == KERNEL_READY_RESPONSE+ assert_kernel_ready_response(data)websocket.close()# Connect by the same session idwith client.websocket_connect("/ws?session_id=123") as websocket:@@ -61,7 +77,7 @@ def test_disconnect_then_reconnect_then_refresh(client: TestClient) -> None:# New session with new ID (simulates refresh)with client.websocket_connect("/ws?session_id=455") as websocket:data = websocket.receive_text()- assert data == KERNEL_READY_RESPONSE+ assert_kernel_ready_response(data)def test_fails_on_multiple_connections_with_other_sessions(@@ -69,7 +85,7 @@ def test_fails_on_multiple_connections_with_other_sessions() -> None:with client.websocket_connect("/ws?session_id=123") as websocket:data = websocket.receive_text()- assert data == KERNEL_READY_RESPONSE+ assert_kernel_ready_response(data)with pytest.raises(WebSocketDisconnect) as exc_info:with client.websocket_connect("/ws?session_id=456"