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: fix RuntimeState to be able to recover from failed ui element updates (#437)

Myles Scolnick1c0619234fe7
diff --git a/frontend/src/components/editor/cell/useRunCells.ts b/frontend/src/components/editor/cell/useRunCells.ts
index 06210022d8..3a8d9c8b1d 100644
--- a/frontend/src/components/editor/cell/useRunCells.ts
+++ b/frontend/src/components/editor/cell/useRunCells.ts
@@ -1,5 +1,5 @@
/* Copyright 2023 Marimo. All rights reserved. */
-import { RuntimeState } from "@/core/RuntimeState";
+import { RuntimeState } from "@/core/kernel/RuntimeState";
import { CellId } from "@/core/cells/ids";
import { sendRun } from "@/core/network/requests";
import { staleCellIds, useNotebook } from "@/core/cells/cells";
diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsx
index f66faab7cf..1b7daf0a6a 100644
--- a/frontend/src/components/editor/renderers/CellArray.tsx
+++ b/frontend/src/components/editor/renderers/CellArray.tsx
@@ -2,7 +2,7 @@
import { useEffect } from "react";
import { sendDeleteCell } from "@/core/network/requests";
import { Cell } from "@/components/editor/Cell";
-import { RuntimeState } from "../../../core/RuntimeState";
+import { RuntimeState } from "../../../core/kernel/RuntimeState";
import {
ConnectionStatus,
WebSocketState,
diff --git a/frontend/src/core/App.tsx b/frontend/src/core/App.tsx
index 433bf9b562..8cea781d15 100644
--- a/frontend/src/core/App.tsx
+++ b/frontend/src/core/App.tsx
@@ -47,7 +47,7 @@ import { SortableCellsProvider } from "../components/sort/SortableCellsProvider"
import { CellId, HTMLCellId } from "./cells/ids";
import { CellConfig } from "./cells/types";
import { CellArray } from "../components/editor/renderers/CellArray";
-import { RuntimeState } from "./RuntimeState";
+import { RuntimeState } from "./kernel/RuntimeState";
import { CellsRenderer } from "../components/editor/renderers/cells-renderer";
import { getSerializedLayout } from "./layout/layout";
import { useAtom } from "jotai";
diff --git a/frontend/src/core/functions/FunctionRegistry.ts b/frontend/src/core/functions/FunctionRegistry.ts
index 4bf2bc2452..d402137324 100644
--- a/frontend/src/core/functions/FunctionRegistry.ts
+++ b/frontend/src/core/functions/FunctionRegistry.ts
@@ -1,6 +1,6 @@
/* Copyright 2023 Marimo. All rights reserved. */
-import { RuntimeState } from "@/core/RuntimeState";
+import { RuntimeState } from "@/core/kernel/RuntimeState";
import { sendFunctionRequest } from "@/core/network/requests";
import { FunctionCallResultMessage } from "../kernel/messages";
import { DeferredRequestRegistry } from "../network/DeferredRequestRegistry";
diff --git a/frontend/src/core/RuntimeState.ts b/frontend/src/core/kernel/RuntimeState.ts
similarity index 56%
rename from frontend/src/core/RuntimeState.ts
rename to frontend/src/core/kernel/RuntimeState.ts
index 254b35eb7d..8e81914c19 100644
--- a/frontend/src/core/RuntimeState.ts
+++ b/frontend/src/core/kernel/RuntimeState.ts
@@ -1,8 +1,12 @@
/* Copyright 2023 Marimo. All rights reserved. */
import { sendComponentValues } from "@/core/network/requests";
-import { marimoValueReadyEvent, MarimoValueReadyEventType } from "./dom/events";
-import { UI_ELEMENT_REGISTRY, UIElementRegistry } from "./dom/uiregistry";
-import { isStaticNotebook } from "./static/static-state";
+import {
+ marimoValueReadyEvent,
+ MarimoValueReadyEventType,
+} from "../dom/events";
+import { UI_ELEMENT_REGISTRY, UIElementRegistry } from "../dom/uiregistry";
+import { isStaticNotebook } from "../static/static-state";
+import { RunRequests } from "../network/types";
/**
* Manager to track running cells.
@@ -11,7 +15,9 @@ export class RuntimeState {
/**
* Shared instance of RuntimeState since this must be a singleton.
*/
- static readonly INSTANCE = new RuntimeState(UI_ELEMENT_REGISTRY);
+ static readonly INSTANCE = new RuntimeState(UI_ELEMENT_REGISTRY, {
+ sendComponentValues,
+ });
// TODO(akshayka): move the running-count state machine to the Python kernel;
// keeping track of it in the frontend is very brittle. the kernel can simply
@@ -26,7 +32,12 @@ export class RuntimeState {
*/
private componentsToUpdate: Set<string>;
- private constructor(private uiElementRegistry: UIElementRegistry) {
+ constructor(
+ private uiElementRegistry: UIElementRegistry,
+ private opts: {
+ sendComponentValues: RunRequests["sendComponentValues"];
+ }
+ ) {
this.runningCount = 0;
this.componentsToUpdate = new Set();
}
@@ -61,14 +72,30 @@ export class RuntimeState {
flushUpdates() {
if (this.componentsToUpdate.size > 0) {
+ // Start a run
this.registerRunStart();
- sendComponentValues(
- Array.from(this.componentsToUpdate.values(), (objectId) => ({
- objectId: objectId,
- value: this.uiElementRegistry.lookupValue(objectId),
- })).filter((update) => update.value !== undefined)
- );
+ // Store the components to update, in case the run fails to be sent
+ const previousComponentsToUpdate = new Set(this.componentsToUpdate);
+
+ this.opts
+ .sendComponentValues(
+ Array.from(this.componentsToUpdate.values(), (objectId) => ({
+ objectId: objectId,
+ value: this.uiElementRegistry.lookupValue(objectId),
+ })).filter((update) => update.value !== undefined)
+ )
+ .catch(() => {
+ // This happens if the run was failed ot register (403, network error, etc.)
+ // If the run fails, restore the components to update and finish the run
+ // A run may fail if the kernel is restarted or the notebook is closed,
+ // but if we don't restore registerRunEnd() will never be able to flush updates.
+ this.registerRunEnd();
+ // Merge the previous components to update with the current ones
+ previousComponentsToUpdate.forEach((objectId) =>
+ this.componentsToUpdate.add(objectId)
+ );
+ });
this.componentsToUpdate.clear();
}
}
diff --git a/frontend/src/core/kernel/__tests__/RuntimeState.test.ts b/frontend/src/core/kernel/__tests__/RuntimeState.test.ts
new file mode 100644
index 0000000000..01970f6126
--- /dev/null
+++ b/frontend/src/core/kernel/__tests__/RuntimeState.test.ts
@@ -0,0 +1,174 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { marimoValueReadyEvent } from "@/core/dom/events";
+import { UIElementRegistry } from "@/core/dom/uiregistry";
+import { describe, beforeEach, expect, vi, test, MockedFunction } from "vitest";
+import { RuntimeState } from "../RuntimeState";
+import { RunRequests } from "@/core/network/types";
+import { UIElementId } from "@/core/cells/ids";
+
+const elementOne = document.createElement("div");
+const uiElementOneId = "uiElementOne" as UIElementId;
+const elementTwo = document.createElement("div");
+const uiElementTwoId = "uiElementTwo" as UIElementId;
+
+const addEventListenerSpy = vi.spyOn(document, "addEventListener");
+const removeEventListenerSpy = vi.spyOn(document, "removeEventListener");
+
+describe("RuntimeState", () => {
+ let runtimeState: RuntimeState;
+ let mockSendComponentValues: MockedFunction<
+ RunRequests["sendComponentValues"]
+ >;
+ let uiElementRegistry: UIElementRegistry;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockSendComponentValues = vi.fn((args) => Promise.resolve(null));
+ uiElementRegistry = UIElementRegistry.INSTANCE;
+ uiElementRegistry.entries.clear();
+
+ runtimeState = new RuntimeState(uiElementRegistry, {
+ sendComponentValues: mockSendComponentValues,
+ });
+ });
+
+ test("start should register event listener", () => {
+ runtimeState.start();
+ expect(addEventListenerSpy).toHaveBeenCalledWith(
+ marimoValueReadyEvent,
+ expect.any(Function)
+ );
+ });
+
+ test("stop should remove event listener", () => {
+ runtimeState.stop();
+ expect(removeEventListenerSpy).toHaveBeenCalledWith(
+ marimoValueReadyEvent,
+ expect.any(Function)
+ );
+ });
+
+ test("registerRunStart should increment runningCount", () => {
+ runtimeState.registerRunStart();
+ expect(runtimeState.running()).toBe(true);
+ });
+
+ test("registerRunEnd should decrement runningCount", () => {
+ runtimeState.registerRunStart();
+ runtimeState.registerRunStart();
+ runtimeState.registerRunEnd();
+ expect(runtimeState.running()).toBe(true); // still running
+ runtimeState.registerRunEnd();
+ expect(runtimeState.running()).toBe(false); // not running
+ });
+
+ test("flushUpdates should not call sendComponentValues if no updates", () => {
+ runtimeState.flushUpdates();
+ expect(mockSendComponentValues).not.toHaveBeenCalled();
+ });
+
+ test("flushUpdates should call sendComponentValues with updates", async () => {
+ runtimeState.start();
+ uiElementRegistry.registerInstance(uiElementOneId, elementOne);
+ expect(uiElementRegistry.entries).toHaveLength(1);
+ expect(mockSendComponentValues).not.toHaveBeenCalled();
+
+ uiElementRegistry.broadcastValueUpdate(elementOne, uiElementOneId, "10");
+ expect(mockSendComponentValues).toHaveBeenCalledOnce();
+ expect(mockSendComponentValues.mock.lastCall?.[0]).toMatchInlineSnapshot(`
+ [
+ {
+ "objectId": "uiElementOne",
+ "value": "10",
+ },
+ ]
+ `);
+ expect(runtimeState.running()).toBe(true);
+ });
+
+ test("will only send one broadcast at a time and hold future events", () => {
+ runtimeState.start();
+ uiElementRegistry.registerInstance(uiElementOneId, elementOne);
+ uiElementRegistry.registerInstance(uiElementTwoId, elementTwo);
+ uiElementRegistry.broadcastValueUpdate(elementOne, uiElementOneId, "10");
+ // Set while running
+ uiElementRegistry.broadcastValueUpdate(elementTwo, uiElementTwoId, "20");
+ uiElementRegistry.broadcastValueUpdate(elementOne, uiElementOneId, "30");
+ expect(mockSendComponentValues).toHaveBeenCalledOnce();
+ expect(mockSendComponentValues.mock.lastCall?.[0]).toMatchInlineSnapshot(`
+ [
+ {
+ "objectId": "uiElementOne",
+ "value": "10",
+ },
+ ]
+ `);
+ expect(runtimeState.running()).toBe(true);
+
+ // End run
+ runtimeState.registerRunEnd();
+ expect(runtimeState.running()).toBe(false);
+
+ // Start another run, this overwrites the previous value that was not sent
+ uiElementRegistry.broadcastValueUpdate(elementTwo, uiElementTwoId, "40");
+ expect(mockSendComponentValues).toHaveBeenCalledTimes(2);
+ // We expect 2 values to be sent, the last value of uiElementTwo and the last value of uiElementOne
+ // both that were set while running
+ expect(mockSendComponentValues.mock.lastCall?.[0]).toMatchInlineSnapshot(`
+ [
+ {
+ "objectId": "uiElementTwo",
+ "value": "40",
+ },
+ {
+ "objectId": "uiElementOne",
+ "value": "30",
+ },
+ ]
+ `);
+ expect(runtimeState.running()).toBe(true);
+ });
+
+ test("handle when sendComponentValues fails", async () => {
+ runtimeState.start();
+ uiElementRegistry.registerInstance(uiElementOneId, elementOne);
+ uiElementRegistry.registerInstance(uiElementTwoId, elementTwo);
+ expect(uiElementRegistry.entries).toHaveLength(2);
+ expect(mockSendComponentValues).not.toHaveBeenCalled();
+
+ const error = new Error("Failed to send component values");
+ mockSendComponentValues.mockRejectedValueOnce(error);
+
+ uiElementRegistry.broadcastValueUpdate(elementOne, uiElementOneId, "10");
+ // flush the event loop
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(mockSendComponentValues).toHaveBeenCalledOnce();
+ expect(mockSendComponentValues.mock.lastCall?.[0]).toMatchInlineSnapshot(`
+ [
+ {
+ "objectId": "uiElementOne",
+ "value": "10",
+ },
+ ]
+ `);
+
+ // It should not be running anymore
+ expect(runtimeState.running()).toBe(false);
+
+ // And if we try another element, we should send both (since the previous one failed)
+ uiElementRegistry.broadcastValueUpdate(elementTwo, uiElementTwoId, "20");
+ expect(mockSendComponentValues).toHaveBeenCalledTimes(2);
+ expect(mockSendComponentValues.mock.lastCall?.[0]).toMatchInlineSnapshot(`
+ [
+ {
+ "objectId": "uiElementOne",
+ "value": "10",
+ },
+ {
+ "objectId": "uiElementTwo",
+ "value": "20",
+ },
+ ]
+ `);
+ });
+});
diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsx
index 2ee0f5b844..28bb07c215 100644
--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx
+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx
@@ -5,7 +5,7 @@ import { connectionAtom } from "../network/connection";
import { useWebSocket } from "@/core/websocket/useWebSocket";
import { logNever } from "@/utils/assertNever";
import { useCellActions } from "@/core/cells/cells";
-import { RuntimeState } from "@/core/RuntimeState";
+import { RuntimeState } from "@/core/kernel/RuntimeState";
import { AUTOCOMPLETER } from "@/core/codemirror/completion/Autocompleter";
import { UI_ELEMENT_REGISTRY } from "@/core/dom/uiregistry";
import { OperationMessage } from "@/core/kernel/messages";