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: Save cell execution times for session resume (#1619)

Wasim Sandhu45bc83e3a951
diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsx
index ee1ef5f14a..0b8baa1542 100644
--- a/frontend/src/components/editor/renderers/CellArray.tsx
+++ b/frontend/src/components/editor/renderers/CellArray.tsx
@@ -30,6 +30,7 @@ import { aiEnabledAtom, autoInstantiateAtom } from "@/core/config/config";
import { useAtomValue } from "jotai";
import { useBoolean } from "@/hooks/useBoolean";
import { AddCellWithAI } from "../ai/add-cell-with-ai";
+import { Milliseconds } from "@/utils/time";
interface CellArrayProps {
notebook: NotebookState;
@@ -122,7 +123,9 @@ export const CellArray: React.FC<CellArrayProps> = ({
stopped={cell.stopped}
staleInputs={cell.staleInputs}
runStartTimestamp={cell.runStartTimestamp}
- runElapsedTimeMs={cell.runElapsedTimeMs}
+ runElapsedTimeMs={
+ cell.runElapsedTimeMs ?? (cell.lastExecutionTime as Milliseconds)
+ }
serializedEditorState={cell.serializedEditorState}
showDeleteButton={cells.length > 1 && !cell.config.hide_code}
createNewCell={createNewCell}
diff --git a/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap b/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap
index 1150eabb63..b110163ab8 100644
--- a/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap
+++ b/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap
@@ -11,6 +11,7 @@ exports[`cell reducer > can initialize stdin 1`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": null,
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -34,6 +35,7 @@ exports[`cell reducer > can initialize stdin 2`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -57,6 +59,7 @@ exports[`cell reducer > can initialize stdin 3`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -80,6 +83,7 @@ exports[`cell reducer > can initialize stdin 4`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -110,6 +114,7 @@ exports[`cell reducer > can initialize stdin 5`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -140,6 +145,7 @@ exports[`cell reducer > can initialize stdin 6`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -176,6 +182,7 @@ exports[`cell reducer > can initialize stdin 7`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -213,6 +220,7 @@ exports[`cell reducer > can initialize stdin 8`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -256,6 +264,7 @@ exports[`cell reducer > can initialize stdin 9`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -279,6 +288,7 @@ exports[`cell reducer > can receive console when the cell is idle and will clear
"id": "0",
"interrupted": false,
"lastCodeRun": null,
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -309,6 +319,7 @@ exports[`cell reducer > can receive console when the cell is idle and will clear
"id": "0",
"interrupted": false,
"lastCodeRun": "",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -339,6 +350,7 @@ exports[`cell reducer > can receive console when the cell is idle and will clear
"id": "0",
"interrupted": false,
"lastCodeRun": "",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -362,6 +374,7 @@ exports[`cell reducer > can receive console when the cell is idle and will clear
"id": "0",
"interrupted": false,
"lastCodeRun": "",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -392,6 +405,7 @@ exports[`cell reducer > can receive console when the cell is idle and will clear
"id": "0",
"interrupted": false,
"lastCodeRun": "",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -415,6 +429,7 @@ exports[`cell reducer > can run a stale cell 1`] = `
"id": "1",
"interrupted": false,
"lastCodeRun": "mo.slider()",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -438,6 +453,7 @@ exports[`cell reducer > can run a stale cell 2`] = `
"id": "1",
"interrupted": false,
"lastCodeRun": "mo.slider()",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -461,6 +477,7 @@ exports[`cell reducer > can run a stopped cell 1`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "mo.md('This has an ancestor that was stopped')",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -484,6 +501,7 @@ exports[`cell reducer > can run a stopped cell 2`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "mo.md('This has an ancestor that was stopped')",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -507,6 +525,7 @@ exports[`cell reducer > can run a stopped cell 3`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "mo.md('This has an ancestor that was stopped')",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": {
@@ -541,6 +560,7 @@ exports[`cell reducer > can run a stopped cell 4`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "mo.md('This has an ancestor that was stopped')",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": {
@@ -575,6 +595,7 @@ exports[`cell reducer > can run a stopped cell 5`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "mo.md('This has an ancestor that was stopped')",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -598,6 +619,7 @@ exports[`cell reducer > can run cell and receive cell messages 1`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": null,
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -621,6 +643,7 @@ exports[`cell reducer > can run cell and receive cell messages 2`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": null,
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -644,6 +667,7 @@ exports[`cell reducer > can run cell and receive cell messages 3`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "import marimo as mo",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -667,6 +691,7 @@ exports[`cell reducer > can run cell and receive cell messages 4`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "import marimo as mo",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -690,6 +715,7 @@ exports[`cell reducer > can run cell and receive cell messages 5`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "import marimo as mo",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -720,6 +746,7 @@ exports[`cell reducer > can run cell and receive cell messages 6`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "import marimo as mo",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": null,
@@ -750,6 +777,7 @@ exports[`cell reducer > can run cell and receive cell messages 7`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "import marimo as mo",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": {
@@ -786,6 +814,7 @@ import numpy",
"id": "0",
"interrupted": false,
"lastCodeRun": "import marimo as mo",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": {
@@ -821,6 +850,7 @@ exports[`cell reducer > can run cell and receive cell messages 9`] = `
"id": "0",
"interrupted": false,
"lastCodeRun": "import marimo as mo",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": {
@@ -857,6 +887,7 @@ import numpy",
"id": "0",
"interrupted": false,
"lastCodeRun": "import marimo as mo",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": {
@@ -894,6 +925,7 @@ import numpy",
"interrupted": false,
"lastCodeRun": "import marimo as mo
import numpy",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": {
@@ -937,6 +969,7 @@ import numpy",
"interrupted": true,
"lastCodeRun": "import marimo as mo
import numpy",
+ "lastExecutionTime": null,
"name": "__",
"outline": null,
"output": {
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 6619356118..38af95e937 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -111,6 +111,7 @@ function initialNotebookState(): NotebookState {
code: deserializeBase64(code),
edited: false,
lastCodeRun: null,
+ lastExecutionTime: null,
config: deserializeJson(deserializeBase64(config)),
serializedEditorState: null,
};
@@ -161,6 +162,7 @@ const {
before: boolean;
code?: string;
lastCodeRun?: string;
+ lastExecutionTime?: number;
newCellId?: CellId;
autoFocus?: boolean;
},
@@ -170,6 +172,7 @@ const {
before,
code,
lastCodeRun = null,
+ lastExecutionTime = null,
autoFocus = true,
} = action;
const newCellId = action.newCellId || CellId.create();
@@ -188,6 +191,7 @@ const {
id: newCellId,
code,
lastCodeRun,
+ lastExecutionTime,
edited: Boolean(code) && code !== lastCodeRun,
}),
},
@@ -451,6 +455,7 @@ const {
...cell,
edited: false,
lastCodeRun: cell.code.trim(),
+ lastExecutionTime: cell.lastExecutionTime,
};
});
},
diff --git a/frontend/src/core/cells/types.ts b/frontend/src/core/cells/types.ts
index 086a429195..27bf46e579 100644
--- a/frontend/src/core/cells/types.ts
+++ b/frontend/src/core/cells/types.ts
@@ -28,6 +28,7 @@ export function createCell({
name = DEFAULT_CELL_NAME,
code = "",
lastCodeRun = null,
+ lastExecutionTime = null,
edited = false,
config = {},
serializedEditorState = null,
@@ -39,6 +40,7 @@ export function createCell({
code: code,
edited: edited,
lastCodeRun: lastCodeRun,
+ lastExecutionTime: lastExecutionTime,
serializedEditorState: serializedEditorState,
};
}
@@ -72,6 +74,8 @@ export interface CellData {
edited: boolean;
/** snapshot of code that was last run */
lastCodeRun: string | null;
+ /** last execution time */
+ lastExecutionTime: number | null;
/** cell configuration */
config: CellConfig;
/** serialized state of the underlying editor */
diff --git a/frontend/src/core/kernel/handlers.ts b/frontend/src/core/kernel/handlers.ts
index 2b3c117707..676535cfeb 100644
--- a/frontend/src/core/kernel/handlers.ts
+++ b/frontend/src/core/kernel/handlers.ts
@@ -40,6 +40,7 @@ export function handleKernelReady(
ui_values,
cell_ids,
last_executed_code = {},
+ last_execution_time = {},
app_config,
} = data;
@@ -65,6 +66,7 @@ export function handleKernelReady(
edited: edited,
name: names[i],
lastCodeRun: last_executed_code[cellId] ?? null,
+ lastExecutionTime: last_execution_time[cellId] ?? null,
config: configs[i],
});
});
diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.ts
index 79c0da6c49..e2610872e8 100644
--- a/frontend/src/core/kernel/messages.ts
+++ b/frontend/src/core/kernel/messages.ts
@@ -256,6 +256,10 @@ export type OperationMessage =
* The last executed code
*/
last_executed_code: Record<CellId, string | undefined> | undefined;
+ /**
+ * The last execution time
+ */
+ last_execution_time: Record<CellId, number> | undefined;
/**
* App config
*/
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.py
index f7f6448375..02ee9f4d9c 100644
--- a/marimo/_messaging/ops.py
+++ b/marimo/_messaging/ops.py
@@ -338,6 +338,8 @@ class KernelReady(Op):
ui_values: Optional[Dict[str, JSONType]]
# If the kernel was resumed, the last executed code for each cell
last_executed_code: Optional[Dict[CellId_t, str]]
+ # If the kernel was resumed, the last execution time for each cell
+ last_execution_time: Optional[Dict[CellId_t, float]]
# App config
app_config: _AppConfig
diff --git a/marimo/_pyodide/bootstrap.py b/marimo/_pyodide/bootstrap.py
index 2409e8ac50..31a7ff6d1a 100644
--- a/marimo/_pyodide/bootstrap.py
+++ b/marimo/_pyodide/bootstrap.py
@@ -74,6 +74,7 @@ def create_session(
resumed=False,
ui_values={},
last_executed_code={},
+ last_execution_time={},
app_config=app.config,
)
),
diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.py
index 5faf6964f7..63a0edfbf9 100644
--- a/marimo/_server/api/endpoints/ws.py
+++ b/marimo/_server/api/endpoints/ws.py
@@ -115,6 +115,7 @@ class WebsocketHandler(SessionConsumer):
resumed: bool,
ui_values: dict[str, JSONType],
last_executed_code: dict[CellId_t, str],
+ last_execution_time: dict[CellId_t, float],
) -> None:
"""Communicates to the client that the kernel is ready.
@@ -154,6 +155,7 @@ class WebsocketHandler(SessionConsumer):
)
last_executed_code = {}
+ last_execution_time = {}
await self.message_queue.put(
(
@@ -168,6 +170,7 @@ class WebsocketHandler(SessionConsumer):
resumed=resumed,
ui_values=ui_values,
last_executed_code=last_executed_code,
+ last_execution_time=last_execution_time,
app_config=app.config,
)
),
@@ -213,6 +216,7 @@ class WebsocketHandler(SessionConsumer):
resumed=True,
ui_values=session.get_current_state().ui_values,
last_executed_code=session.get_current_state().last_executed_code,
+ last_execution_time=session.get_current_state().last_execution_time,
)
await self.write_operation(
Banner(
@@ -305,7 +309,11 @@ class WebsocketHandler(SessionConsumer):
self.status = ConnectionState.OPEN
# Let the frontend know it can instantiate the app.
await self._write_kernel_ready(
- new_session, resumed=False, ui_values={}, last_executed_code={}
+ new_session,
+ resumed=False,
+ ui_values={},
+ last_executed_code={},
+ last_execution_time={},
)
return new_session
diff --git a/marimo/_server/session/session_view.py b/marimo/_server/session/session_view.py
index 5845a34b3a..d013e6c328 100644
--- a/marimo/_server/session/session_view.py
+++ b/marimo/_server/session/session_view.py
@@ -1,8 +1,9 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import time
from dataclasses import dataclass
-from typing import Any, Optional, Union
+from typing import Any, Literal, Optional, Union
from marimo._ast.cell import CellId_t
from marimo._data.models import DataTable
@@ -46,6 +47,8 @@ class SessionView:
self.ui_values: dict[str, Any] = {}
# Map of cell id to the last code that was executed in that cell.
self.last_executed_code: dict[CellId_t, str] = {}
+ # Map of cell id to the last cell execution time
+ self.last_execution_time: dict[CellId_t, float] = {}
def _add_ui_value(self, name: str, value: Any) -> None:
self.ui_values[name] = value
@@ -98,6 +101,13 @@ class SessionView:
self.cell_operations[operation.cell_id] = merge_cell_operation(
previous, operation
)
+ if not previous:
+ return
+ if previous.status == "queued" and operation.status == "running":
+ self.save_execution_time(operation, "start")
+ if previous.status == "running" and operation.status == "idle":
+ self.save_execution_time(operation, "end")
+
elif isinstance(operation, Variables):
self.variable_operations = operation
@@ -156,6 +166,24 @@ class SessionView:
outputs[cell_id] = as_list(cell_op.console)
return outputs
+ def save_execution_time(
+ self, operation: MessageOperation, event: Literal["start", "end"]
+ ) -> None:
+ """Updates execution time for given cell."""
+ if not isinstance(operation, CellOp):
+ return
+ cell_id = operation.cell_id
+
+ if event == "start":
+ time_elapsed = operation.timestamp
+ elif event == "end":
+ start = self.last_execution_time.get(cell_id)
+ start = start if start else 0
+ time_elapsed = time.time() - start
+ time_elapsed = round(time_elapsed * 1000)
+
+ self.last_execution_time[cell_id] = time_elapsed
+
@property
def operations(self) -> list[MessageOperation]:
all_ops: list[MessageOperation] = [
diff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.py
index 1a93c171a5..777be60619 100644
--- a/tests/_server/api/endpoints/test_resume_session.py
+++ b/tests/_server/api/endpoints/test_resume_session.py
@@ -1,9 +1,10 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import time
from typing import TYPE_CHECKING, Any, Optional
-from marimo._messaging.ops import KernelReady
+from marimo._messaging.ops import CellOp, KernelReady
from marimo._server.sessions import Session
from marimo._utils.parse_dataclass import parse_raw
from tests._server.conftest import get_session_manager
@@ -24,6 +25,7 @@ def create_response(
"resumed": False,
"ui_values": {},
"last_executed_code": {},
+ "last_execution_time": {},
"configs": [{"disabled": False, "hide_code": False}],
"app_config": {"width": "full"},
}
@@ -56,6 +58,7 @@ def assert_kernel_ready_response(
assert data.ui_values == expected.ui_values
assert data.configs == expected.configs
assert data.app_config == expected.app_config
+ assert data.last_execution_time == expected.last_execution_time
def get_session(client: TestClient, session_id: str) -> Optional[Session]:
@@ -68,7 +71,16 @@ def test_refresh_session(client: TestClient) -> None:
assert_kernel_ready_response(data, create_response({}))
# Check the session still exists after closing the websocket
- assert get_session(client, "123")
+ session = get_session(client, "123")
+ session_view = session.session_view
+ assert session
+
+ # Mimic cell execution time save
+ cell_op = CellOp("Hbol")
+ session_view.save_execution_time(cell_op, "start")
+ time.sleep(0.123)
+ session_view.save_execution_time(cell_op, "end")
+ last_exec_time = session_view.last_execution_time["Hbol"]
# New session with new ID (simulates refresh)
# We should resume the current session
@@ -78,7 +90,15 @@ def test_refresh_session(client: TestClient) -> None:
assert data == {"op": "reconnected", "data": {}}
# Resume the session
data = websocket.receive_json()
- assert_kernel_ready_response(data, create_response({"resumed": True}))
+ assert_kernel_ready_response(
+ data,
+ create_response(
+ {
+ "resumed": True,
+ "last_execution_time": {"Hbol": last_exec_time},
+ }
+ ),
+ )
# Send a value to the kernel
response = client.post(
"/api/kernel/set_ui_element_value",
@@ -111,6 +131,7 @@ def test_refresh_session(client: TestClient) -> None:
"ui-element-2": "value2",
},
"resumed": True,
+ "last_execution_time": {"Hbol": last_exec_time},
}
),
)
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index ba61d667f6..bbfee468b6 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -29,6 +29,7 @@ def create_response(
"resumed": False,
"ui_values": {},
"last_executed_code": {},
+ "last_execution_time": {},
"configs": [{"disabled": False, "hide_code": False}],
"app_config": {"width": "full"},
}