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: reasonable session and notebook merge (#5335)

Dylan Madisetti58e145ad85df
diff --git a/biome.jsonc b/biome.jsonc
index 23ca0b7731..81d746838f 100644
--- a/biome.jsonc
+++ b/biome.jsonc
@@ -1,7 +1,7 @@
{
"$schema": "frontend/node_modules/@biomejs/biome/configuration_schema.json",
"files": {
- "includes": ["frontend/src/**/*", "!*.json"]
+ "includes": ["frontend/src/**/*", "openapi/**/*", "lsp/**/*", "!*.json"]
},
"formatter": {
"indentStyle": "space",
diff --git a/frontend/src/components/editor/RecoveryButton.tsx b/frontend/src/components/editor/RecoveryButton.tsx
index d5c5e4eb5f..1e3b006147 100644
--- a/frontend/src/components/editor/RecoveryButton.tsx
+++ b/frontend/src/components/editor/RecoveryButton.tsx
@@ -46,6 +46,7 @@ const RecoveryModal = (props: {
id: cell.id,
name: cell.name,
code: cell.code,
+ code_hash: null,
config: {
column: 0,
...cell.config,
diff --git a/frontend/src/core/cells/__tests__/session.test.ts b/frontend/src/core/cells/__tests__/session.test.ts
index 1e5544af77..ef2d360d1b 100644
--- a/frontend/src/core/cells/__tests__/session.test.ts
+++ b/frontend/src/core/cells/__tests__/session.test.ts
@@ -40,9 +40,10 @@ describe("notebookStateFromSession", () => {
id: string,
outputs: SessionCell["outputs"] = [],
console: SessionCell["console"] = [],
+ code_hash: string | null = null,
): SessionCell => ({
id,
- code_hash: null,
+ code_hash,
outputs,
console,
});
@@ -52,9 +53,11 @@ describe("notebookStateFromSession", () => {
code: string | null = null,
name: string | null = null,
config: NotebookCell["config"] | null = null,
+ code_hash: string | null = null,
): NotebookCell => ({
id,
code,
+ code_hash: code_hash,
name,
config: {
column: config?.column ?? null,
@@ -91,10 +94,15 @@ describe("notebookStateFromSession", () => {
const result = notebookStateFromSession(session, notebook);
- expect(Logger.error).toHaveBeenCalledWith(
- "Session and notebook must have the same cells if both are provided",
+ expect(Logger.warn).toHaveBeenCalledWith(
+ "Session and notebook have different cells, attempted merge.",
+ );
+ // Should have the same cell structure as notebook
+ expect(result).not.toBeNull();
+ invariant(result, "result is null");
+ expect(result.cellIds.inOrderIds).toEqual(
+ MultiColumn.from([["cell-2"]]).inOrderIds,
);
- expect(result).toBeNull();
});
});
@@ -125,7 +133,7 @@ describe("notebookStateFromSession", () => {
expect(result.cellIds.inOrderIds).toEqual(
MultiColumn.from([[CELL_1]]).inOrderIds,
);
- expect(result.cellData[CELL_1]).toBeUndefined();
+ expect(result.cellData[CELL_1].code).toBe("");
expect(result.cellRuntime[CELL_1]).toBeDefined();
});
@@ -141,7 +149,10 @@ describe("notebookStateFromSession", () => {
expect(result.cellIds.inOrderIds).toEqual(
MultiColumn.from([["cell-1", "cell-2"]]).inOrderIds,
);
- expect(Object.keys((result as any).cellData)).toEqual([]);
+ expect(Object.keys((result as any).cellData)).toEqual([
+ "cell-1",
+ "cell-2",
+ ]);
expect(Object.keys((result as any).cellRuntime)).toEqual([
"cell-1",
"cell-2",
@@ -310,6 +321,7 @@ describe("notebookStateFromSession", () => {
id: "cell-1",
code: null,
name: null,
+ code_hash: null,
config: {
hide_code: null,
disabled: null,
@@ -553,4 +565,193 @@ describe("notebookStateFromSession", () => {
expect(result.cellLogs).toEqual([]);
});
});
+
+ describe("session and notebook merge with code values abcdef", () => {
+ it("merges session and notebook with code values a-f and correct hashes", () => {
+ // md5 hashes for 'a' through 'f'
+ const hashes = {
+ a: "0cc175b9c0f1b6a831c399e269772661",
+ b: "92eb5ffee6ae2fec3ad71c777531578f",
+ c: "4a8a08f09d37b73795649038408b5f33",
+ d: "8277e0910d750195b448797616e091ad",
+ e: "e1671797c52e15f763380b45e841ec32",
+ f: "8fa14cdd754f91cc6554c9e71929cce7",
+ };
+ // Create notebook cells with code values 'a' through 'f'
+ const notebookCells = [
+ createNotebookCell("cell-a", "a", null, null, hashes.a),
+ createNotebookCell("cell-b", "b", null, null, hashes.b),
+ createNotebookCell("cell-c", "c", null, null, hashes.c),
+ createNotebookCell("cell-d", "d", null, null, hashes.d),
+ createNotebookCell("cell-e", "e", null, null, hashes.e),
+ createNotebookCell("cell-f", "f", null, null, hashes.f),
+ ];
+ // Create session cells with matching code_hashes
+ const sessionCells = [
+ createSessionCell(
+ "cell-a",
+ [{ type: "data", data: { "text/plain": "A!" } }],
+ [],
+ hashes.a,
+ ),
+ createSessionCell(
+ "cell-b",
+ [{ type: "data", data: { "text/plain": "B!" } }],
+ [],
+ hashes.b,
+ ),
+ createSessionCell(
+ "cell-c",
+ [{ type: "data", data: { "text/plain": "C!" } }],
+ [],
+ hashes.c,
+ ),
+ createSessionCell(
+ "cell-d",
+ [{ type: "data", data: { "text/plain": "D!" } }],
+ [],
+ hashes.d,
+ ),
+ createSessionCell(
+ "cell-e",
+ [{ type: "data", data: { "text/plain": "E!" } }],
+ [],
+ hashes.e,
+ ),
+ createSessionCell(
+ "cell-f",
+ [{ type: "data", data: { "text/plain": "F!" } }],
+ [],
+ hashes.f,
+ ),
+ ];
+ const session = createSession(sessionCells);
+ const notebook = createNotebook(notebookCells);
+ const result = notebookStateFromSession(session, notebook);
+ expect(result).not.toBeNull();
+ invariant(result, "result is null");
+ // Should have all cell IDs in order
+ expect(result.cellIds.inOrderIds).toEqual(
+ MultiColumn.from([
+ ["cell-a", "cell-b", "cell-c", "cell-d", "cell-e", "cell-f"],
+ ]).inOrderIds,
+ );
+ // Should have correct code and output for each cell
+ for (const code of ["a", "b", "c", "d", "e", "f"]) {
+ const cellId = `cell-${code}` as CellId;
+ expect(result.cellData[cellId].code).toBe(code);
+ expect(result.cellRuntime[cellId].output).toEqual({
+ channel: "output",
+ data: `${code.toUpperCase()}!`,
+ mimetype: "text/plain",
+ timestamp: 0,
+ });
+ }
+ });
+
+ it("merges session and notebook with abcde -> aczeg edit distance scenario", () => {
+ // md5 hashes for the codes
+ const hashes = {
+ a: "0cc175b9c0f1b6a831c399e269772661",
+ b: "92eb5ffee6ae2fec3ad71c777531578f",
+ c: "4a8a08f09d37b73795649038408b5f33",
+ d: "8277e0910d750195b448797616e091ad",
+ e: "e1671797c52e15f763380b45e841ec32",
+ z: "fbade9e36a3f36d3d676c1b808451dd7", // hash for 'z'
+ g: "b2f5ff47436671b6e533d8dc3614845d", // hash for 'g'
+ };
+
+ // Session has cells with code 'a', 'b', 'c', 'd', 'e'
+ const sessionCells = [
+ createSessionCell(
+ "cell-a",
+ [{ type: "data", data: { "text/plain": "A!" } }],
+ [],
+ hashes.a,
+ ),
+ createSessionCell(
+ "cell-b",
+ [{ type: "data", data: { "text/plain": "B!" } }],
+ [],
+ hashes.b,
+ ),
+ createSessionCell(
+ "cell-c",
+ [{ type: "data", data: { "text/plain": "C!" } }],
+ [],
+ hashes.c,
+ ),
+ createSessionCell(
+ "cell-d",
+ [{ type: "data", data: { "text/plain": "D!" } }],
+ [],
+ hashes.d,
+ ),
+ createSessionCell(
+ "cell-e",
+ [{ type: "data", data: { "text/plain": "E!" } }],
+ [],
+ hashes.e,
+ ),
+ ];
+
+ // Notebook has cells with code 'a', 'c', 'z', 'e', 'g'
+ const notebookCells = [
+ createNotebookCell("cell-a", "a", null, null, hashes.a),
+ createNotebookCell("cell-c", "c", null, null, hashes.c),
+ createNotebookCell("cell-z", "z", null, null, hashes.z),
+ createNotebookCell("cell-e", "e", null, null, hashes.e),
+ createNotebookCell("cell-g", "g", null, null, hashes.g),
+ ];
+
+ const session = createSession(sessionCells);
+ const notebook = createNotebook(notebookCells);
+ const result = notebookStateFromSession(session, notebook);
+
+ expect(result).not.toBeNull();
+ invariant(result, "result is null");
+
+ // Should have notebook cell IDs in order (notebook is canonical)
+ expect(result.cellIds.inOrderIds).toEqual(
+ MultiColumn.from([["cell-a", "cell-c", "cell-z", "cell-e", "cell-g"]])
+ .inOrderIds,
+ );
+
+ // Should have correct code for each cell
+ expect(result.cellData["cell-a" as CellId].code).toBe("a");
+ expect(result.cellData["cell-c" as CellId].code).toBe("c");
+ expect(result.cellData["cell-z" as CellId].code).toBe("z");
+ expect(result.cellData["cell-e" as CellId].code).toBe("e");
+ expect(result.cellData["cell-g" as CellId].code).toBe("g");
+
+ // Should have session outputs for matching cells (a, c, e)
+ expect(result.cellRuntime["cell-a" as CellId].output).toEqual({
+ channel: "output",
+ data: "A!",
+ mimetype: "text/plain",
+ timestamp: 0,
+ });
+ expect(result.cellRuntime["cell-c" as CellId].output).toEqual({
+ channel: "output",
+ data: "C!",
+ mimetype: "text/plain",
+ timestamp: 0,
+ });
+ expect(result.cellRuntime["cell-e" as CellId].output).toEqual({
+ channel: "output",
+ data: "E!",
+ mimetype: "text/plain",
+ timestamp: 0,
+ });
+
+ // Should have no output for new cells (z, g) - they get stub session cells
+ expect(result.cellRuntime["cell-z" as CellId].output).toBeNull();
+ expect(result.cellRuntime["cell-g" as CellId].output).toBeNull();
+
+ // Should log warning about different cells
+ expect(Logger.warn).toHaveBeenCalledWith(
+ "Session and notebook have different cells, attempted merge.",
+ );
+ });
+ });
});
diff --git a/frontend/src/core/cells/session.ts b/frontend/src/core/cells/session.ts
index f1577bdd8f..badf525c8a 100644
--- a/frontend/src/core/cells/session.ts
+++ b/frontend/src/core/cells/session.ts
@@ -1,9 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
import type * as api from "@marimo-team/marimo-api";
+import { mergeArray } from "@/utils/edit-distance";
import { MultiColumn } from "@/utils/id-tree";
import { Logger } from "@/utils/Logger";
-import { Sets } from "@/utils/sets";
import { parseOutline } from "../dom/outline";
import { CellId } from "./ids";
import {
@@ -19,60 +19,133 @@ const EMPTY_STRING = "";
type SessionCell = api.Session["NotebookSessionV1"]["cells"][0];
type NotebookCell = api.Notebook["NotebookV1"]["cells"][0];
-interface ValidationResult {
- isValid: boolean;
- error?: string;
-}
-
-function validateSessionNotebookCompatibility(
+function mergeSessionAndNotebookCells(
session: api.Session["NotebookSessionV1"] | null | undefined,
notebook: api.Notebook["NotebookV1"] | null | undefined,
-): ValidationResult {
+): {
+ cellIds: CellId[];
+ sessionCellData: Map<CellId, SessionCell | null>;
+ notebookCellData: Map<CellId, NotebookCell>;
+} {
+ const sessionCellData = new Map<CellId, SessionCell | null>();
+ const notebookCellData = new Map<CellId, NotebookCell>();
+
if (!session && !notebook) {
+ return { cellIds: [], sessionCellData, notebookCellData };
+ }
+
+ if (!session) {
+ const cellIds = (notebook?.cells.map(
+ (cell) => cell.id ?? CellId.create(),
+ ) || []) as CellId[];
return {
- isValid: false,
- error: "",
+ cellIds,
+ sessionCellData: new Map(
+ cellIds.map((id, idx) => [id, null] as [CellId, SessionCell | null]),
+ ),
+ notebookCellData: new Map(
+ cellIds.map(
+ (id, idx) =>
+ [id, notebook?.cells[idx] || createEmptyNotebookCell()] as [
+ CellId,
+ NotebookCell,
+ ],
+ ),
+ ),
};
}
- if (!session || !notebook) {
- return { isValid: true }; // One is null, which is fine
+ if (!notebook) {
+ const cellIds = session.cells.map(
+ (cell) => cell.id ?? CellId.create(),
+ ) as CellId[];
+ return {
+ cellIds,
+ sessionCellData: new Map(
+ cellIds.map(
+ (id, idx) => [id, session.cells[idx]] as [CellId, SessionCell | null],
+ ),
+ ),
+ notebookCellData: new Map(
+ cellIds.map(
+ (id) => [id, createEmptyNotebookCell()] as [CellId, NotebookCell],
+ ),
+ ),
+ };
}
- const sessionCellIds = new Set(session.cells.map((cell) => cell.id));
- const notebookCellIds = new Set(notebook.cells.map((cell) => cell.id));
+ // Both session and notebook exist - merge using edit distance on cell content
+ // hash.
+ const { merged: mergedSessionCells, edits } = mergeArray(
+ session.cells,
+ notebook.cells,
+ (sessionCell, notebookCell) => {
+ const sessionCodeHash = sessionCell.code_hash;
+ // If the code hash is null, default to comparing ids
+ if (!sessionCodeHash) {
+ return sessionCell.id === notebookCell.id;
+ }
+ // Compare session cell code_hash with notebook cell code
+ const notebookCodeHash = notebookCell.code_hash;
+ return notebookCodeHash === sessionCodeHash;
+ },
+ // stub cell is empty session cell
+ createEmptySessionCell(),
+ );
+ if (edits.distance > 0) {
+ Logger.warn("Session and notebook have different cells, attempted merge.");
+ }
- // Only check they are equal if both are provided
- if (
- sessionCellIds.size > 0 &&
- notebookCellIds.size > 0 &&
- !Sets.equals(sessionCellIds, notebookCellIds)
- ) {
- return {
- isValid: false,
- error:
- "Session and notebook must have the same cells if both are provided",
- };
+ // Create merged cell arrays
+ const mergedCellIdsTyped: CellId[] = [];
+
+ // Defer to the notebook cells for the correct ordering.
+ for (let i = 0; i < notebook.cells.length; i++) {
+ const notebookCell = notebook.cells[i];
+ if (notebookCell) {
+ const id = (notebookCell.id ?? CellId.create()) as CellId;
+ mergedCellIdsTyped.push(id);
+
+ // Should always be set, but good typing fallback too.
+ const sessionItem = mergedSessionCells[i] || createEmptySessionCell();
+ sessionItem.id = id; // Ensure session cell has the correct ID
+
+ sessionCellData.set(id, sessionItem);
+ notebookCellData.set(id, notebookCell);
+ } else {
+ // This shouldn't happen since notebook cells are canonical
+ Logger.warn("Merged notebook cell is null at index", i);
+ }
}
- return { isValid: true };
+ return {
+ cellIds: mergedCellIdsTyped,
+ sessionCellData,
+ notebookCellData,
+ };
}
-function getCellIds(
- session: api.Session["NotebookSessionV1"] | null | undefined,
- notebook: api.Notebook["NotebookV1"] | null | undefined,
-): CellId[] {
- // Prefer notebook cells (for ordering) over session cells if both are provided
- const ids = (notebook?.cells.map((cell) => cell.id) ??
- session?.cells.map((cell) => cell.id) ??
- []) as CellId[];
- // Replace nulls with unique ids.
- return ids.map((id) => {
- if (id === null) {
- return CellId.create();
- }
- return id;
- });
+function createEmptyNotebookCell(): NotebookCell {
+ return {
+ id: CellId.create(),
+ name: EMPTY_STRING,
+ code: EMPTY_STRING,
+ code_hash: null,
+ config: {
+ column: null,
+ disabled: false,
+ hide_code: false,
+ },
+ };
+}
+
+function createEmptySessionCell(): SessionCell {
+ return {
+ id: CellId.create(),
+ code_hash: null,
+ console: [],
+ outputs: [],
+ };
}
function createCellDataFromNotebook(
@@ -154,32 +227,15 @@ export function notebookStateFromSession(
session: api.Session["NotebookSessionV1"] | null | undefined,
notebook: api.Notebook["NotebookV1"] | null | undefined,
) {
- // Validate compatibility
- const validation = validateSessionNotebookCompatibility(session, notebook);
- if (!validation.isValid) {
- if (validation.error) {
- Logger.error(validation.error);
- }
- return null;
- }
+ // Merge session and notebook cells using edit distance
+ const { cellIds, sessionCellData, notebookCellData } =
+ mergeSessionAndNotebookCells(session, notebook);
- // Get cell IDs
- const cellIds = getCellIds(session, notebook);
if (cellIds.length === 0) {
Logger.warn("Session and notebook must have at least one cell");
return null;
}
- // Create lookup maps for efficient access
- // Replacing with the cellIds fallback.
- const sessionCellData = new Map(
- cellIds.map((id, idx) => [id, session?.cells[idx]]),
- );
-
- const notebookCellData = new Map(
- cellIds.map((id, idx) => [id, notebook?.cells[idx]]),
- );
-
const cellData: Record<CellId, CellData> = {};
const cellRuntime: Record<CellId, CellRuntimeState> = {};
diff --git a/frontend/src/utils/__tests__/edit-distance.test.ts b/frontend/src/utils/__tests__/edit-distance.test.ts
new file mode 100644
index 0000000000..b0d54fc561
--- /dev/null
+++ b/frontend/src/utils/__tests__/edit-distance.test.ts
@@ -0,0 +1,302 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { describe, expect, it } from "vitest";
+import {
+ applyOperationsWithStub,
+ type EditOperation,
+ editDistance,
+ editDistanceGeneral,
+ mergeArray,
+ OperationType,
+} from "../edit-distance";
+
+describe("editDistance", () => {
+ it("should return distance 0 for identical arrays", () => {
+ const arr1 = ["a", "b", "c"];
+ const arr2 = ["a", "b", "c"];
+ const result = editDistance(arr1, arr2);
+
+ expect(result.distance).toBe(0);
+ expect(result.operations).toHaveLength(3);
+ expect(
+ result.operations.every((op) => op.type === OperationType.MATCH),
+ ).toBe(true);
+ });
+
+ it("should handle empty arrays", () => {
+ const result1 = editDistance([], []);
+ expect(result1.distance).toBe(0);
+ expect(result1.operations).toHaveLength(0);
+
+ const result2 = editDistance(["a"], []);
+ expect(result2.distance).toBe(1);
+ expect(result2.operations).toHaveLength(1);
+ expect(result2.operations[0].type).toBe(OperationType.DELETE);
+
+ const result3 = editDistance([], ["a"]);
+ expect(result3.distance).toBe(1);
+ expect(result3.operations).toHaveLength(1);
+ expect(result3.operations[0].type).toBe(OperationType.INSERT);
+ });
+
+ it("should handle single element differences", () => {
+ const arr1 = ["a", "b", "c"];
+ const arr2 = ["a", "b", "d"];
+ const result = editDistance(arr1, arr2);
+
+ expect(result.distance).toBe(1);
+ expect(result.operations).toHaveLength(3);
+ expect(result.operations[0].type).toBe(OperationType.MATCH);
+ expect(result.operations[1].type).toBe(OperationType.MATCH);
+ expect(result.operations[2].type).toBe(OperationType.SUBSTITUTE);
+ });
+
+ it("should handle insertions and deletions", () => {
+ const arr1 = ["a", "b", "c"];
+ const arr2 = ["a", "x", "b", "c"];
+ const result = editDistance(arr1, arr2);
+
+ expect(result.distance).toBe(1);
+ expect(result.operations).toHaveLength(4);
+ expect(result.operations[0].type).toBe(OperationType.MATCH);
+ expect(result.operations[1].type).toBe(OperationType.INSERT);
+ expect(result.operations[2].type).toBe(OperationType.MATCH);
+ expect(result.operations[3].type).toBe(OperationType.MATCH);
+ });
+
+ it("should work with custom equality function", () => {
+ const arr1 = [
+ { id: 1, name: "a" },
+ { id: 2, name: "b" },
+ ];
+ const arr2 = [
+ { id: 1, name: "a" },
+ { id: 3, name: "c" },
+ ];
+
+ const result = editDistanceGeneral(arr1, arr2, (a, b) => a.id === b.id);
+
+ expect(result.distance).toBe(1);
+ expect(result.operations).toHaveLength(2);
+ expect(result.operations[0].type).toBe(OperationType.MATCH);
+ expect(result.operations[1].type).toBe(OperationType.SUBSTITUTE);
+ });
+
+ // Test the specific example mentioned by the user
+ it("should handle the specific example: abcde -> aczeg", () => {
+ const arr1 = ["a", "b", "c", "d", "e"];
+ const arr2 = ["a", "c", "z", "e", "g"];
+ const result = editDistance(arr1, arr2);
+
+ expect(result.distance).toBe(3);
+ expect(result.operations).toHaveLength(6);
+
+ // Expected operations: match, delete, match, sub, match, insert
+ expect(result.operations[0].type).toBe(OperationType.MATCH); // 'a'
+ expect(result.operations[1].type).toBe(OperationType.DELETE); // 'b'
+ expect(result.operations[2].type).toBe(OperationType.MATCH); // 'c'
+ expect(result.operations[3].type).toBe(OperationType.SUBSTITUTE); // 'd' -> 'z'
+ expect(result.operations[4].type).toBe(OperationType.MATCH); // 'e'
+ expect(result.operations[5].type).toBe(OperationType.INSERT); // 'g'
+ });
+});
+
+describe("applyOperationsWithStub", () => {
+ it("should apply match operations correctly", () => {
+ const original = ["a", "b", "c"];
+ const operations: EditOperation[] = [
+ { type: OperationType.MATCH, position: 0 },
+ { type: OperationType.MATCH, position: 1 },
+ { type: OperationType.MATCH, position: 2 },
+ ];
+
+ const result = applyOperationsWithStub(original, operations, "stub");
+ expect(result).toEqual(["a", "b", "c"]);
+ });
+
+ it("should apply delete operations correctly", () => {
+ const original = ["a", "b", "c"];
+ const operations: EditOperation[] = [
+ { type: OperationType.MATCH, position: 0 },
+ { type: OperationType.DELETE, position: 1 },
+ { type: OperationType.MATCH, position: 2 },
+ ];
+
+ const result = applyOperationsWithStub(original, operations, "stub");
+ expect(result).toEqual(["a", "c"]);
+ });
+
+ it("should apply insert operations correctly", () => {
+ const original = ["a", "c"];
+ const operations: EditOperation[] = [
+ { type: OperationType.MATCH, position: 0 },
+ { type: OperationType.INSERT, position: 1 },
+ { type: OperationType.MATCH, position: 1 },
+ ];
+
+ const result = applyOperationsWithStub(original, operations, "stub");
+ expect(result).toEqual(["a", "stub", "c"]);
+ });
+
+ it("should apply substitute operations correctly", () => {
+ const original = ["a", "b", "c"];
+ const operations: EditOperation[] = [
+ { type: OperationType.MATCH, position: 0 },
+ {
+ type: OperationType.SUBSTITUTE,
+ position: 1,
+ },
+ { type: OperationType.MATCH, position: 2 },
+ ];
+
+ const result = applyOperationsWithStub(original, operations, "stub");
+ expect(result).toEqual(["a", "stub", "c"]);
+ });
+
+ it("should handle complex operations with position offsets", () => {
+ const original = ["a", "b", "c", "d"];
+ const operations: EditOperation[] = [
+ { type: OperationType.MATCH, position: 0 },
+ { type: OperationType.DELETE, position: 1 },
+ { type: OperationType.INSERT, position: 1 },
+ { type: OperationType.MATCH, position: 2 },
+ { type: OperationType.DELETE, position: 3 },
+ ];
+
+ const result = applyOperationsWithStub(original, operations, "stub");
+ expect(result).toEqual(["a", "stub", "c"]);
+ });
+
+ // Test the specific example mentioned by the user
+ it("should handle the specific example: abcde -> ac_e_ (with stub)", () => {
+ const original = ["a", "b", "c", "d", "e"];
+ const operations: EditOperation[] = [
+ { type: OperationType.MATCH, position: 0 },
+ { type: OperationType.DELETE, position: 1 },
+ { type: OperationType.MATCH, position: 2 },
+ {
+ type: OperationType.SUBSTITUTE,
+ position: 3,
+ },
+ { type: OperationType.MATCH, position: 4 },
+ { type: OperationType.INSERT, position: 5 },
+ ];
+
+ const result = applyOperationsWithStub(original, operations, "_");
+ expect(result).toEqual(["a", "c", "_", "e", "_"]);
+ });
+
+ it("should handle multiple consecutive operations correctly", () => {
+ const original = ["a", "b", "c"];
+ const operations: EditOperation[] = [
+ { type: OperationType.DELETE, position: 0 },
+ { type: OperationType.INSERT, position: 0 },
+ {
+ type: OperationType.SUBSTITUTE,
+ position: 1,
+ },
+ { type: OperationType.DELETE, position: 2 },
+ ];
+
+ const result = applyOperationsWithStub(original, operations, "stub");
+ // After DELETE at position 0: ["b", "c"] (offset = -1)
+ // After INSERT at position 0: ["stub", "b", "c"] (offset = 0)
+ // After SUBSTITUTE at position 1: ["stub", "stub", "c"] (offset = 0)
+ // After DELETE at position 2: ["stub", "stub"] (offset = -1)
+ expect(result).toEqual(["stub", "stub"]);
+ });
+
+ it("should handle operations that affect array length", () => {
+ const original = ["a", "b"];
+ const operations: EditOperation[] = [
+ { type: OperationType.INSERT, position: 0 },
+ { type: OperationType.INSERT, position: 1 },
+ { type: OperationType.MATCH, position: 2 },
+ { type: OperationType.MATCH, position: 3 },
+ { type: OperationType.INSERT, position: 4 },
+ ];
+
+ const result = applyOperationsWithStub(original, operations, "stub");
+ // After INSERT at position 0: ["stub", "a", "b"] (offset = 1)
+ // After INSERT at position 1: ["stub", "stub", "a", "b"] (offset = 2)
+ // After MATCH at position 2: ["stub", "stub", "a", "b"] (offset = 2)
+ // After MATCH at position 3: ["stub", "stub", "a", "b"] (offset = 2)
+ // After INSERT at position 4: ["stub", "stub", "a", "b", "stub"] (offset = 3)
+ expect(result).toEqual(["stub", "stub", "a", "b", "stub"]);
+ });
+});
+
+describe("mergeArray", () => {
+ it("should merge arrays with matching elements", () => {
+ const arr1 = ["a", "b", "c"];
+ const arr2 = ["a", "b", "c"];
+ const stub = "stub";
+
+ const result = mergeArray(arr1, arr2, (a, b) => a === b, stub);
+
+ expect(result.merged).toEqual(["a", "b", "c"]);
+ expect(result.edits.distance).toBe(0);
+ });
+
+ it("should merge arrays with different elements", () => {
+ const arr1 = ["a", "b", "c"];
+ const arr2 = ["a", "x", "c"];
+ const stub = "stub";
+
+ const result = mergeArray(arr1, arr2, (a, b) => a === b, stub);
+
+ expect(result.merged).toEqual(["a", "stub", "c"]);
+ expect(result.edits.distance).toBe(1);
+ });
+
+ it("should handle empty arrays", () => {
+ const arr1: string[] = [];
+ const arr2: string[] = [];
+ const stub = "stub";
+
+ const result = mergeArray(arr1, arr2, () => false, stub);
+
+ expect(result.merged).toEqual([]);
+ expect(result.edits.distance).toBe(0);
+ });
+
+ it("should handle one empty array", () => {
+ const arr1 = ["a", "b"];
+ const arr2: string[] = [];
+ const stub = "stub";
+
+ const result = mergeArray(arr1, arr2, () => false, stub);
+
+ expect(result.merged).toEqual([]);
+ expect(result.edits.distance).toBe(2);
+ });
+
+ it("should handle complex merging scenarios", () => {
+ const arr1 = ["a", "b", "c"];
+ const arr2 = ["a", "x", "y", "c"];
+ const stub = "stub";
+
+ const result = mergeArray(arr1, arr2, (a, b) => a === b, stub);
+
+ expect(result.merged).toEqual(["a", "stub", "stub", "c"]);
+ expect(result.edits.distance).toBe(2);
+ });
+
+ it("should handle the specific example: abcde -> aczeg", () => {
+ const arr1 = ["a", "b", "c", "d", "e"];
+ const arr2 = ["a", "c", "z", "e", "g"];
+ const stub = "_";
+
+ const result = mergeArray(arr1, arr2, (a, b) => a === b, stub);
+
+ // For abcde -> aczeg:
+ // a matches a -> keep a
+ // b is deleted -> skip b
+ // c matches c -> keep c
+ // d is substituted with z -> use stub _
+ // e matches e -> keep e
+ // g is inserted -> use stub _
+ expect(result.merged).toEqual(["a", "c", "_", "e", "_"]);
+ expect(result.edits.distance).toBe(3);
+ });
+});
diff --git a/frontend/src/utils/edit-distance.ts b/frontend/src/utils/edit-distance.ts
new file mode 100644
index 0000000000..c11615a277
--- /dev/null
+++ b/frontend/src/utils/edit-distance.ts
@@ -0,0 +1,141 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+export enum OperationType {
+ INSERT = "insert",
+ DELETE = "delete",
+ SUBSTITUTE = "substitute",
+ MATCH = "match",
+}
+
+export interface EditOperation {
+ type: OperationType;
+ position: number;
+}
+
+export interface EditDistanceResult {
+ distance: number;
+ operations: EditOperation[];
+}
+
+export function editDistanceGeneral<T, U>(
+ arr1: T[],
+ arr2: U[],
+ equals: (a: T, b: U) => boolean,
+): EditDistanceResult {
+ const m: number = arr1.length;
+ const n: number = arr2.length;
+
+ const dp: number[][] = Array.from({ length: m + 1 }, () =>
+ Array.from<number>({ length: n + 1 }).fill(0),
+ );
+
+ for (let i = 0; i <= m; i++) {
+ dp[i][0] = i;
+ }
+ for (let j = 0; j <= n; j++) {
+ dp[0][j] = j;
+ }
+
+ for (let i = 1; i <= m; i++) {
+ for (let j = 1; j <= n; j++) {
+ dp[i][j] = equals(arr1[i - 1], arr2[j - 1])
+ ? dp[i - 1][j - 1]
+ : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
+ }
+ }
+
+ // Backtrack for operations
+ const operations: EditOperation[] = [];
+ let i: number = m;
+ let j: number = n;
+
+ while (i > 0 || j > 0) {
+ if (i > 0 && j > 0 && equals(arr1[i - 1], arr2[j - 1])) {
+ operations.unshift({
+ type: OperationType.MATCH,
+ position: i - 1,
+ });
+ i--;
+ j--;
+ } else if (i > 0 && j > 0 && dp[i][j] === dp[i - 1][j - 1] + 1) {
+ operations.unshift({
+ type: OperationType.SUBSTITUTE,
+ position: i - 1,
+ });
+ i--;
+ j--;
+ } else if (i > 0 && dp[i][j] === dp[i - 1][j] + 1) {
+ operations.unshift({
+ type: OperationType.DELETE,
+ position: i - 1,
+ });
+ i--;
+ } else if (j > 0 && dp[i][j] === dp[i][j - 1] + 1) {
+ operations.unshift({
+ type: OperationType.INSERT,
+ position: i,
+ });
+ j--;
+ }
+ }
+
+ return { distance: dp[m][n], operations };
+}
+
+export function editDistance<T>(arr1: T[], arr2: T[]): EditDistanceResult {
+ // Default equality check for primitive types
+ const equals = (a: T, b: T): boolean => a === b;
+ return editDistanceGeneral(arr1, arr2, equals);
+}
+
+// Function to apply operations with stub for inserts/substitutions
+export function applyOperationsWithStub<T>(
+ originalArray: T[],
+ operations: EditOperation[],
+ stub: T,
+): T[] {
+ const result: T[] = [];
+ let originalIndex = 0;
+
+ for (const op of operations) {
+ switch (op.type) {
+ case OperationType.MATCH:
+ // Copy the original element
+ result.push(originalArray[originalIndex]);
+ originalIndex++;
+ break;
+
+ case OperationType.DELETE:
+ // Skip the original element (don't add to result)
+ originalIndex++;
+ break;
+
+ case OperationType.INSERT:
+ // Add stub for inserted element
+ result.push(stub);
+ break;
+
+ case OperationType.SUBSTITUTE:
+ // Add stub for substituted element
+ result.push(stub);
+ originalIndex++;
+ break;
+ }
+ }
+
+ return result;
+}
+
+// Generic function to merge cell arrays by code content
+export function mergeArray<T, U>(
+ arr1: T[],
+ arr2: U[],
+ equals: (a: T, b: U) => boolean,
+ stub: T,
+): { merged: Array<T | null>; edits: EditDistanceResult } {
+ const edits = editDistanceGeneral(arr1, arr2, equals);
+ return {
+ merged: applyOperationsWithStub(arr1, edits.operations, stub),
+ edits,
+ };
+}
diff --git a/lsp/index.test.ts b/lsp/index.test.ts
index 1ac34de0a6..798c2903a1 100644
--- a/lsp/index.test.ts
+++ b/lsp/index.test.ts
@@ -1,5 +1,5 @@
import { spawn } from "node:child_process";
-import { describe, it, expect } from "vitest";
+import { describe, expect, it } from "vitest";
describe("LSP Server", () => {
it("should start and be killable", async () => {
diff --git a/lsp/index.ts b/lsp/index.ts
index c82d8baa8f..8e3afec0e7 100644
--- a/lsp/index.ts
+++ b/lsp/index.ts
@@ -1,12 +1,12 @@
+import fsSync from "node:fs";
+import fs from "node:fs/promises";
import type * as http from "node:http";
+import path from "node:path";
+import type * as rpc from "@sourcegraph/vscode-ws-jsonrpc";
+import * as rpcServer from "@sourcegraph/vscode-ws-jsonrpc/lib/server";
import parseArgs from "minimist";
import type ws from "ws";
import { WebSocketServer } from "ws";
-import type * as rpc from "@sourcegraph/vscode-ws-jsonrpc";
-import * as rpcServer from "@sourcegraph/vscode-ws-jsonrpc/lib/server";
-import path from "node:path";
-import fs from "node:fs/promises";
-import fsSync from "node:fs";
const LOG_FILE = path.join(
process.env.XDG_CACHE_HOME || path.join(process.env.HOME || "", ".cache"),
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index 8940a0a684..afa38110d7 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -12,6 +12,7 @@ import click
from marimo._cli.print import orange
from marimo._convert.converters import MarimoConvert
+from marimo._utils.code import hash_code
if TYPE_CHECKING:
import psutil
@@ -535,7 +536,6 @@ def preview(file_path: Path, port: int, host: str, headless: bool) -> None:
NotebookSessionMetadata,
NotebookSessionV1,
)
- from marimo._server.export.exporter import hash_code
from marimo._server.templates.templates import static_notebook_template
from marimo._server.tokens import SkewProtectionToken
from marimo._utils.paths import marimo_package_path
@@ -577,8 +577,8 @@ def preview(file_path: Path, port: int, host: str, headless: bool) -> None:
app_config=_AppConfig(),
filepath=str(file_path),
code=code,
- code_hash=hash_code(code),
session_snapshot=session_snapshot,
+ code_hash=hash_code(code),
notebook_snapshot=notebook_snapshot,
files={},
asset_url=asset_url,
diff --git a/marimo/_convert/notebook.py b/marimo/_convert/notebook.py
index e82ec97145..1683b0441b 100644
--- a/marimo/_convert/notebook.py
+++ b/marimo/_convert/notebook.py
@@ -12,6 +12,7 @@ from marimo._schemas.serialization import (
NotebookSerialization,
NotebookSerializationV1,
)
+from marimo._utils.code import hash_code
def convert_from_ir_to_notebook_v1(
@@ -31,6 +32,7 @@ def convert_from_ir_to_notebook_v1(
NotebookCell(
id=None,
code=data.code,
+ code_hash=hash_code(data.code) if data.code else None,
name=data.name,
config=NotebookCellConfig(
column=data.options.get("column", None),
diff --git a/marimo/_schemas/generated/notebook.yaml b/marimo/_schemas/generated/notebook.yaml
index 1451e5042d..b0a2139a24 100644
--- a/marimo/_schemas/generated/notebook.yaml
+++ b/marimo/_schemas/generated/notebook.yaml
@@ -6,6 +6,9 @@ components:
code:
nullable: true
type: string
+ code_hash:
+ nullable: true
+ type: string
config:
properties:
column:
@@ -27,6 +30,7 @@ components:
required:
- id
- code
+ - code_hash
- name
- config
type: object
diff --git a/marimo/_schemas/notebook.py b/marimo/_schemas/notebook.py
index d6e5390efc..548ee9b38c 100644
--- a/marimo/_schemas/notebook.py
+++ b/marimo/_schemas/notebook.py
@@ -24,6 +24,7 @@ class NotebookCell(TypedDict):
id: Optional[str]
code: Optional[str]
+ code_hash: Optional[str]
name: Optional[str]
config: NotebookCellConfig
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index 2c13b4ff8d..5f8b24b842 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -52,6 +52,7 @@ from marimo._server.templates.templates import (
)
from marimo._server.tokens import SkewProtectionToken
from marimo._types.ids import CellId_t
+from marimo._utils.code import hash_code
from marimo._utils.data_uri import build_data_url
from marimo._utils.marimo_path import MarimoPath
from marimo._utils.paths import marimo_package_path
@@ -541,12 +542,6 @@ class AutoExporter:
self._executor.shutdown(wait=False)
-def hash_code(code: str) -> str:
- import hashlib
-
- return hashlib.sha256(code.encode("utf-8")).hexdigest()
-
-
def _create_notebook_cell(
cell: CellImpl, outputs: list[NotebookNode]
) -> NotebookNode:
diff --git a/marimo/_server/session/serialize.py b/marimo/_server/session/serialize.py
index 598929a75b..2843dd58ba 100644
--- a/marimo/_server/session/serialize.py
+++ b/marimo/_server/session/serialize.py
@@ -223,6 +223,7 @@ def serialize_notebook(
NotebookCell(
id=cell_id,
code=code,
+ code_hash=_hash_code(code),
name=name,
config=config,
)
diff --git a/marimo/_utils/code.py b/marimo/_utils/code.py
new file mode 100644
index 0000000000..149d2b9797
--- /dev/null
+++ b/marimo/_utils/code.py
@@ -0,0 +1,7 @@
+# Copyright 2025 Marimo. All rights reserved.
+
+
+def hash_code(code: str) -> str:
+ import hashlib
+
+ return hashlib.sha256(code.encode("utf-8")).hexdigest()
diff --git a/openapi/src/index.ts b/openapi/src/index.ts
index dad853e52f..f94d7335d1 100644
--- a/openapi/src/index.ts
+++ b/openapi/src/index.ts
@@ -1,9 +1,9 @@
export type * from "./api";
-import type { components as session } from "./session";
-import type { components as notebook } from "./notebook";
import createClient, { type ClientOptions } from "openapi-fetch";
import type { paths } from "./api";
+import type { components as notebook } from "./notebook";
+import type { components as session } from "./session";
export type Session = session["schemas"];
export type Notebook = notebook["schemas"];
diff --git a/openapi/src/notebook.ts b/openapi/src/notebook.ts
index 835d6045a9..9b3f7ebe52 100644
--- a/openapi/src/notebook.ts
+++ b/openapi/src/notebook.ts
@@ -9,6 +9,7 @@ export interface components {
schemas: {
NotebookCell: {
code: string | null;
+ code_hash: string | null;
config: {
column?: number | null;
disabled?: boolean | null;
diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txt
index a768b4d87c..1db573dcd0 100644
--- a/tests/_server/templates/snapshots/export1.txt
+++ b/tests/_server/templates/snapshots/export1.txt
@@ -63,7 +63,7 @@
"configOverrides": {"formatting": {"line_length": 100}},
"appConfig": {"sql_output": "auto", "width": "compact"},
"view": {"showAppCode": true},
- "notebook": {"cells": [{"code": "print('Hello, Cell 1')", "config": {}, "id": "cell1", "name": "Cell 1"}, {"code": "print('Hello, Cell 2')", "config": {}, "id": "cell2", "name": "Cell 2"}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
+ "notebook": {"cells": [{"code": "print('Hello, Cell 1')", "code_hash": "dd79c4410b5ac8e7ed32b54c7ebd1cda575d9a41770f739b9b8ed19a2a50ff87", "config": {}, "id": "cell1", "name": "Cell 1"}, {"code": "print('Hello, Cell 2')", "code_hash": "9f00c511e0ed7fe6413b8f4d19876bf064117d56109d22d4f8d7f7b1d426c1f9", "config": {}, "id": "cell2", "name": "Cell 2"}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
"session": {"cells": [{"code_hash": "abc123", "console": [{"name": "stdout", "text": "Hello, Cell 1", "type": "stream"}, {"name": "stderr", "text": "Error in Cell 1", "type": "stream"}], "id": "cell1", "outputs": [{"data": {"text/plain": "Hello, Cell 1"}, "type": "data"}]}, {"code_hash": "def456", "console": [], "id": "cell2", "outputs": []}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
"runtimeConfig": null,
};
diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txt
index 4ab724b425..fbaea1dc71 100644
--- a/tests/_server/templates/snapshots/export2.txt
+++ b/tests/_server/templates/snapshots/export2.txt
@@ -63,7 +63,7 @@
"configOverrides": {"formatting": {"line_length": 100}},
"appConfig": {"sql_output": "auto", "width": "compact"},
"view": {"showAppCode": true},
- "notebook": {"cells": [{"code": "print('Hello, Cell 1')", "config": {}, "id": "cell1", "name": "Cell 1"}, {"code": "print('Hello, Cell 2')", "config": {}, "id": "cell2", "name": "Cell 2"}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
+ "notebook": {"cells": [{"code": "print('Hello, Cell 1')", "code_hash": "dd79c4410b5ac8e7ed32b54c7ebd1cda575d9a41770f739b9b8ed19a2a50ff87", "config": {}, "id": "cell1", "name": "Cell 1"}, {"code": "print('Hello, Cell 2')", "code_hash": "9f00c511e0ed7fe6413b8f4d19876bf064117d56109d22d4f8d7f7b1d426c1f9", "config": {}, "id": "cell2", "name": "Cell 2"}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
"session": {"cells": [{"code_hash": "abc123", "console": [{"name": "stdout", "text": "Hello, Cell 1", "type": "stream"}, {"name": "stderr", "text": "Error in Cell 1", "type": "stream"}], "id": "cell1", "outputs": [{"data": {"text/plain": "Hello, Cell 1"}, "type": "data"}]}, {"code_hash": "def456", "console": [], "id": "cell2", "outputs": []}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
"runtimeConfig": null,
};
diff --git a/tests/_server/templates/test_templates.py b/tests/_server/templates/test_templates.py
index 06f38f1460..0bc02bf0f0 100644
--- a/tests/_server/templates/test_templates.py
+++ b/tests/_server/templates/test_templates.py
@@ -27,10 +27,10 @@ from marimo._schemas.session import (
NotebookSessionV1,
StreamOutput,
)
-from marimo._server.export.exporter import hash_code
from marimo._server.model import SessionMode
from marimo._server.templates import templates
from marimo._server.tokens import SkewProtectionToken
+from marimo._utils.code import hash_code
from tests._server.templates.utils import normalize_index_html
from tests.mocks import snapshotter
@@ -370,12 +370,14 @@ class TestStaticNotebookTemplate(unittest.TestCase):
NotebookCell(
id="cell1",
code="print('Hello, Cell 1')",
+ code_hash=hash_code("print('Hello, Cell 1')"),
name="Cell 1",
config=NotebookCellConfig(),
),
NotebookCell(
id="cell2",
code="print('Hello, Cell 2')",
+ code_hash=hash_code("print('Hello, Cell 2')"),
name="Cell 2",
config=NotebookCellConfig(),
),