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
improvement: allow running any cell when auto-run-on-startup is off (#3119)
Myles Scolnick506c28517ae8
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex 20b3dfd061..e5ac0e91da 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -193,7 +193,6 @@ const CellComponent = (cellConfig.disabled || status === "disabled-transitively";const uninstantiated = isUninstantiated({- autoInstantiate: userConfig.runtime.auto_instantiate,executionTime: runElapsedTimeMs,status,errored,@@ -202,10 +201,7 @@ const CellComponent = (});const needsRun =- uninstantiated ||- edited ||- interrupted ||- (staleInputs && !disabledOrAncestorDisabled);+ edited || interrupted || (staleInputs && !disabledOrAncestorDisabled);const loading = status === "running" || status === "queued";const outputStale = outputIsStale(diff --git a/frontend/src/components/editor/cell/useRunCells.ts b/frontend/src/components/editor/cell/useRunCells.tsindex 545bc0eca9..8693bb2839 100644--- a/frontend/src/components/editor/cell/useRunCells.ts+++ b/frontend/src/components/editor/cell/useRunCells.ts@@ -6,18 +6,13 @@ import useEvent from "react-use-event-hook";import { getEditorCodeAsPython } from "@/core/codemirror/language/utils";import { Logger } from "@/utils/Logger";import { staleCellIds } from "@/core/cells/utils";-import { useAtomValue } from "jotai";-import { autoInstantiateAtom } from "@/core/config/config";/*** Creates a function that runs all cells that have been edited or interrupted.*/export function useRunStaleCells() {- const autoInstantiate = useAtomValue(autoInstantiateAtom);const runCells = useRunCells();- const runStaleCells = useEvent(() =>- runCells(staleCellIds(getNotebook(), autoInstantiate)),- );+ const runStaleCells = useEvent(() => runCells(staleCellIds(getNotebook())));return runStaleCells;}diff --git a/frontend/src/core/cells/__tests__/utils.test.ts b/frontend/src/core/cells/__tests__/utils.test.tsindex 0db44b1db2..01c7287be7 100644--- a/frontend/src/core/cells/__tests__/utils.test.ts+++ b/frontend/src/core/cells/__tests__/utils.test.ts@@ -157,7 +157,7 @@ describe("staleCellIds", () => {},} as any;- const result = staleCellIds(state, false);+ const result = staleCellIds(state);expect(result).toEqual(["cell1"]);});@@ -197,7 +197,7 @@ describe("staleCellIds", () => {},} as any;- const result = staleCellIds(state, false);+ const result = staleCellIds(state);expect(result).toEqual(["cell1"]);});@@ -237,7 +237,7 @@ describe("staleCellIds", () => {},} as any;- const result = staleCellIds(state, true);+ const result = staleCellIds(state);expect(result).toEqual(["cell1"]);});@@ -277,7 +277,7 @@ describe("staleCellIds", () => {},} as any;- const result = staleCellIds(state, true);+ const result = staleCellIds(state);expect(result).toEqual(["cell1"]);});@@ -317,7 +317,7 @@ describe("staleCellIds", () => {},} as any;- const result = staleCellIds(state, true);+ const result = staleCellIds(state);expect(result).toEqual([]);});@@ -326,7 +326,6 @@ describe("staleCellIds", () => {describe("isUninstantiated", () => {it("should return true if autoInstantiate is false and cell has not run", () => {const result = isUninstantiated({- autoInstantiate: false,executionTime: null,status: "idle",errored: false,@@ -336,21 +335,8 @@ describe("isUninstantiated", () => {expect(result).toBe(true);});- it("should return false if autoInstantiate is true", () => {- const result = isUninstantiated({- autoInstantiate: true,- executionTime: null,- status: "idle",- errored: false,- interrupted: false,- stopped: false,- });- expect(result).toBe(false);- });-it("should return false if cell has run", () => {const result = isUninstantiated({- autoInstantiate: false,executionTime: 123,status: "idle",errored: false,@@ -362,7 +348,6 @@ describe("isUninstantiated", () => {it("should return false if cell is currently queued or running", () => {let result = isUninstantiated({- autoInstantiate: false,executionTime: null,status: "queued",errored: false,@@ -372,7 +357,6 @@ describe("isUninstantiated", () => {expect(result).toBe(false);result = isUninstantiated({- autoInstantiate: false,executionTime: null,status: "running",errored: false,@@ -384,7 +368,6 @@ describe("isUninstantiated", () => {it("should return false if cell is in an error state", () => {let result = isUninstantiated({- autoInstantiate: false,executionTime: null,status: "idle",errored: true,@@ -394,7 +377,6 @@ describe("isUninstantiated", () => {expect(result).toBe(false);result = isUninstantiated({- autoInstantiate: false,executionTime: null,status: "idle",errored: false,@@ -404,7 +386,6 @@ describe("isUninstantiated", () => {expect(result).toBe(false);result = isUninstantiated({- autoInstantiate: false,executionTime: null,status: "idle",errored: false,diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex 77381dd2ce..15a2a1587b 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -51,7 +51,6 @@ import {} from "@/utils/id-tree";import { isEqual } from "lodash-es";import { isErrorMime } from "../mime";-import { userConfigAtom } from "../config/config";export const SCRATCH_CELL_ID = "__scratch__" as CellId;@@ -1175,12 +1174,7 @@ export const canUndoDeletesAtom = atom((get) =>canUndoDeletes(get(notebookAtom)),);-export const needsRunAtom = atom((get) =>- notebookNeedsRun(- get(notebookAtom),- get(userConfigAtom).runtime.auto_instantiate,- ),-);+export const needsRunAtom = atom((get) => notebookNeedsRun(get(notebookAtom)));const cellErrorsAtom = atom((get) => {const { cellIds, cellRuntime, cellData } = get(notebookAtom);diff --git a/frontend/src/core/cells/utils.ts b/frontend/src/core/cells/utils.tsindex 6a32f95cc7..416f805f23 100644--- a/frontend/src/core/cells/utils.ts+++ b/frontend/src/core/cells/utils.ts@@ -16,11 +16,8 @@ export function notebookQueueOrRunningCount(state: NotebookState) {).length;}-export function notebookNeedsRun(- state: NotebookState,- autoInstantiate: boolean,-) {- return staleCellIds(state, autoInstantiate).length > 0;+export function notebookNeedsRun(state: NotebookState) {+ return staleCellIds(state).length > 0;}export function notebookCells(state: NotebookState) {@@ -92,12 +89,11 @@ export function getDescendantsStatus(state: NotebookState, cellId: CellId) {/*** Cells that are stale and can be run.*/-export function staleCellIds(state: NotebookState, autoInstantiate: boolean) {+export function staleCellIds(state: NotebookState) {const { cellIds, cellData, cellRuntime } = state;return cellIds.inOrderIds.filter((cellId) =>isUninstantiated({- autoInstantiate,// runElapstedTimeMs is what we've seen in this sessionexecutionTime:cellRuntime[cellId].runElapsedTimeMs ??@@ -120,14 +116,12 @@ export function staleCellIds(state: NotebookState, autoInstantiate: boolean) {}export function isUninstantiated({- autoInstantiate,executionTime,status,errored,interrupted,stopped,}: {- autoInstantiate: boolean;executionTime: number | null;status: RuntimeState;errored: boolean;@@ -135,8 +129,6 @@ export function isUninstantiated({stopped: boolean;}) {return (- // autorun on startup is off ...- !autoInstantiate &&// hasn't run ...executionTime === null &&// isn't currently queued/running &&diff --git a/frontend/src/core/kernel/handlers.ts b/frontend/src/core/kernel/handlers.tsindex 5976c4dac3..b8ed7b0286 100644--- a/frontend/src/core/kernel/handlers.ts+++ b/frontend/src/core/kernel/handlers.ts@@ -66,13 +66,9 @@ export function handleKernelReady(// A cell is stale if we did not auto-instantiate (i.e. nothing has run yet)// or if the code has changed since the last time it was run.let edited = false;- if (autoInstantiate || resumed) {- const lastCodeRun = lastExecutedCode[cellId];- if (lastCodeRun) {- edited = lastCodeRun !== code;- }- } else {- edited = true;+ const lastCodeRun = lastExecutedCode[cellId];+ if (lastCodeRun) {+ edited = lastCodeRun !== code;}return createCell({@@ -125,13 +121,14 @@ export function handleKernelReady(objectIds.push(objectId);values.push(entry.value);});- // Send the instantiate message- if (autoInstantiate) {- // Start the run- sendInstantiate({ objectIds: objectIds, values }).catch((error) => {- onError(new Error("Failed to instantiate", { cause: error }));- });- }+ // Start the run+ sendInstantiate({+ objectIds: objectIds,+ values,+ autoRun: autoInstantiate,+ }).catch((error) => {+ onError(new Error("Failed to instantiate", { cause: error }));+ });}export function handleRemoveUIElements(diff --git a/frontend/src/core/wasm/worker/bootstrap.ts b/frontend/src/core/wasm/worker/bootstrap.tsindex d9ad097182..917ffbe29c 100644--- a/frontend/src/core/wasm/worker/bootstrap.ts+++ b/frontend/src/core/wasm/worker/bootstrap.ts@@ -133,8 +133,7 @@ export class DefaultWasmController implements WasmController {)def init(auto_instantiate=True):- if auto_instantiate:- instantiate(session)+ instantiate(session, auto_instantiate)asyncio.create_task(session.start())# Find the packages to installdiff --git a/marimo/_pyodide/bootstrap.py b/marimo/_pyodide/bootstrap.pyindex 607406b5d4..504595c87f 100644--- a/marimo/_pyodide/bootstrap.py+++ b/marimo/_pyodide/bootstrap.py@@ -24,7 +24,9 @@ if TYPE_CHECKING:from marimo._pyodide.pyodide_session import PyodideBridge, PyodideSession-def instantiate(session: PyodideSession) -> None:+def instantiate(+ session: PyodideSession, auto_instantiate: bool = True+) -> None:"""Instantiate the marimo app in the session.@@ -43,6 +45,7 @@ def instantiate(session: PyodideSession) -> None:set_ui_element_value_request=SetUIElementValueRequest(object_ids=[], values=[]),+ auto_run=auto_instantiate,))diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.pyindex 785e8f0ea2..c31d90dd7a 100644--- a/marimo/_runtime/requests.py+++ b/marimo/_runtime/requests.py@@ -128,6 +128,7 @@ class SetUserConfigRequest:class CreationRequest:execution_requests: Tuple[ExecutionRequest, ...]set_ui_element_value_request: SetUIElementValueRequest+ auto_run: bool@dataclassdiff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 5d2f59442a..d7936269bf 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -1292,12 +1292,17 @@ class Kernel:Cells may use top-level await, which is why this function is async."""+ if self.last_interrupt_timestamp is None:+ # No interruption has occurred, so we can run all requests+ await self._run_cells(+ self.mutate_graph(execution_requests, deletion_requests=[])+ )+ return++ # Filter out requests that were created before the last interruptionfiltered_requests: list[ExecutionRequest] = []for request in execution_requests:- if (- self.last_interrupt_timestamp is not None- and request.timestamp < self.last_interrupt_timestamp- ):+ if request.timestamp < self.last_interrupt_timestamp:CellOp.broadcast_error(data=[MarimoInterruptionError()],clear_console=False,@@ -1714,10 +1719,14 @@ class Kernel:During instantiation, UIElements can check for an initial valuewith `get_initial_value`"""+ # Already instantiatedif self.graph.cells:del requestLOGGER.debug("App already instantiated.")- else:+ return++ # Run cells if auto_run is True+ if request.auto_run:self.reset_ui_initializers()for (object_id,@@ -1726,6 +1735,13 @@ class Kernel:self.ui_initializers[object_id] = initial_valueawait self.run(request.execution_requests)self.reset_ui_initializers()+ return++ # Otherwise, just register the cells+ self.mutate_graph(request.execution_requests, deletion_requests=[])+ # and set everything to stale+ for cell_id in self.graph.cells:+ self.graph.cells[cell_id].set_stale(stale=True)async def install_missing_packages(self, request: InstallMissingPackagesRequestdiff --git a/marimo/_server/models/models.py b/marimo/_server/models/models.pyindex 12d212dc7d..90816d5bc2 100644--- a/marimo/_server/models/models.py+++ b/marimo/_server/models/models.py@@ -35,7 +35,7 @@ class UpdateComponentValuesRequest:@dataclassclass InstantiateRequest(UpdateComponentValuesRequest):- pass+ auto_run: bool = True@dataclassdiff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex dc1f11cb33..96b72e3d42 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -623,6 +623,7 @@ class Session:values=request.values,token=str(uuid4()),),+ auto_run=request.auto_run,))diff --git a/marimo/_smoke_tests/auto_instantiate_off.py b/marimo/_smoke_tests/auto_instantiate_off.pynew file mode 100644index 0000000000..8d61211b06--- /dev/null+++ b/marimo/_smoke_tests/auto_instantiate_off.py@@ -0,0 +1,36 @@+import marimo++__generated_with = "0.9.34"+app = marimo.App(width="medium")+++def __():+ import marimo as mo+ return (mo,)+++def __(mo):+ mo.md(r"""If you run this first, then this should run and the `import marimo` cell should run, but nothing else""")+ return+++def __():+ # If you run this first, then this should run, but not `y = x + 1`+ x = 2+ x+ return (x,)+++def __(x):+ # If you run this first, then this should run and `x = 2`+ y = x + 2+ y+ return (y,)+++if __name__ == "__main__":+ app.run()diff --git a/openapi/api.yaml b/openapi/api.yamlindex fb673ab546..c8448601dd 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -329,6 +329,8 @@ components:type: objectCreationRequest:properties:+ autoRun:+ type: booleanexecutionRequests:items:$ref: '#/components/schemas/ExecutionRequest'@@ -338,6 +340,7 @@ components:required:- executionRequests- setUiElementValueRequest+ - autoRuntype: objectCycleError:properties:@@ -851,6 +854,8 @@ components:type: objectInstantiateRequest:properties:+ autoRun:+ type: booleanobjectIds:items:type: string@@ -861,6 +866,7 @@ components:required:- objectIds- values+ - autoRuntype: objectInterrupted:properties:@@ -1924,7 +1930,7 @@ components:type: objectinfo:title: marimo API- version: 0.9.28+ version: 0.9.34openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex a76aba73e3..00e69c3f12 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -2131,6 +2131,7 @@ export interface components {source: string;};CreationRequest: {+ autoRun: boolean;executionRequests: components["schemas"]["ExecutionRequest"][];setUiElementValueRequest: components["schemas"]["SetUIElementValueRequest"];};@@ -2341,6 +2342,7 @@ export interface components {};};InstantiateRequest: {+ autoRun: boolean;objectIds: string[];values: unknown[];};diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex f4e3e52f24..8ae2c641fc 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -337,10 +337,33 @@ class TestExecution:set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values([(id_provider.take_id(), 2)]),+ auto_run=True,))assert k.globals["s"].value == 2+ async def test_instantiate_autorun_false(self, any_kernel: Kernel) -> None:+ k = any_kernel+ await k.instantiate(+ CreationRequest(+ execution_requests=(+ ExecutionRequest(cell_id="0", code="x=0"),+ ExecutionRequest(cell_id="1", code="y=x+1"),+ ),+ set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(+ []+ ),+ auto_run=False,+ )+ )+ assert not k.errors+ assert "x" not in k.globals+ assert "y" not in k.globals++ # Expect the first cell to implicitly be included in the run+ await k.run([ExecutionRequest(cell_id="1", code="y=x+1")])+ assert k.globals["y"] == 1+# Test errors in marimo semanticsasync def test_kernel_simultaneous_multiple_definition_error(self,diff --git a/tests/_server/api/endpoints/test_execution.py b/tests/_server/api/endpoints/test_execution.pyindex 449cc3774d..801277fde0 100644--- a/tests/_server/api/endpoints/test_execution.py+++ b/tests/_server/api/endpoints/test_execution.py@@ -41,6 +41,23 @@ class TestExecutionRoutes_EditMode:json={"object_ids": ["ui-element-1", "ui-element-2"],"values": ["value1", "value2"],+ "auto_run": True,+ },+ )+ assert response.status_code == 200, response.text+ assert response.headers["content-type"] == "application/json"+ assert "success" in response.json()++ @staticmethod+ @with_session(SESSION_ID)+ def test_instantiate_autorun_false(client: TestClient) -> None:+ response = client.post(+ "/api/kernel/instantiate",+ headers=HEADERS,+ json={+ "object_ids": ["ui-element-1", "ui-element-2"],+ "values": ["value1", "value2"],+ "auto_run": False,},)assert response.status_code == 200, response.text@@ -164,6 +181,23 @@ class TestExecutionRoutes_RunMode:json={"object_ids": ["ui-element-1", "ui-element-2"],"values": ["value1", "value2"],+ "auto_run": True,+ },+ )+ assert response.status_code == 200, response.text+ assert response.headers["content-type"] == "application/json"+ assert "success" in response.json()++ @staticmethod+ @with_read_session(SESSION_ID)+ def test_instantiate_autorun_false(client: TestClient) -> None:+ response = client.post(+ "/api/kernel/instantiate",+ headers=HEADERS,+ json={+ "object_ids": ["ui-element-1", "ui-element-2"],+ "values": ["value1", "value2"],+ "auto_run": False,},)assert response.status_code == 200, response.textdiff --git a/tests/_server/session/test_session_view.py b/tests/_server/session/test_session_view.pyindex 567202658b..1dafa1ad45 100644--- a/tests/_server/session/test_session_view.py+++ b/tests/_server/session/test_session_view.py@@ -150,6 +150,7 @@ def test_ui_values() -> None:set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values([("test_ui3", 101112)]),+ auto_run=True,))assert "test_ui3" in session_view.ui_values@@ -184,6 +185,7 @@ def test_last_run_code() -> None:set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values([]),+ auto_run=True,))assert session_view.last_executed_code[cell_id] == "print('hello')"diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.pyindex e47635f9fa..2457f1190a 100644--- a/tests/_server/test_sessions.py+++ b/tests/_server/test_sessions.py@@ -183,6 +183,7 @@ def test_kernel_manager_interrupt(tmp_path) -> None:set_ui_element_value_request=SetUIElementValueRequest(object_ids=[], values=[]),+ auto_run=True,))