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
feat: reactive reloading of modified modules (#1139)
Akshay Agrawalb42bd909f061
diff --git a/Makefile b/Makefileindex a6757d975c..2ef20e43c2 100644--- a/Makefile+++ b/Makefile@@ -67,6 +67,12 @@ py-check:py-test:pytest+.PHONY: py-snapshots+# update html snapshots+py-snapshots:+ pytest tests/_server/templates/test_templates.py+ pytest tests/_server/api/endpoints/test_export.py+.PHONY: install-all# install everything; takes a long time due to editable installinstall-all: fe pydiff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex 2aa13bbe7a..18cc66e581 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -350,20 +350,29 @@ export const UserConfigForm: React.FC = () => {<div className="flex flex-col gap-y-1"><FormItem className="flex flex-row items-start space-x-2 space-y-0"><FormControl>- <Checkbox- data-testid="auto-reload-checkbox"- disabled={field.disabled}- checked={field.value}- onCheckedChange={field.onChange}- />+ <NativeSelect+ data-testid="auto-reload-select"+ onChange={(e) => field.onChange(e.target.value)}+ value={field.value}+ disabled={isWasm}+ className="inline-flex mr-2"+ >+ {["off", "detect", "autorun"].map((option) => (+ <option value={option} key={option}>+ {option}+ </option>+ ))}+ </NativeSelect></FormControl><FormLabel className="font-normal">Autoreload modules</FormLabel></FormItem><FormDescription>- When checked, marimo will automatically reload modules before- executing cells.+ Whether marimo should automatically reload modules before+ executing cells. If "detect", marimo will mark cells affected+ by module modifications as stale; if "automatic", affected+ cells will be automatically re-run.</FormDescription></div>)}diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex 3a5527a8a6..e81f74419a 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -70,6 +70,7 @@ export interface CellProps| "errored"| "interrupted"| "stopped"+ | "staleInputs"| "runStartTimestamp"| "runElapsedTimeMs"| "debuggerActive"@@ -123,6 +124,7 @@ const CellComponent = (interrupted,errored,stopped,+ staleInputs,serializedEditorState,mode,debuggerActive,@@ -154,17 +156,20 @@ const CellComponent = (const editorView = useRef<EditorView | null>(null);const setAiCompletionCell = useSetAtom(aiCompletionCellAtom);- const needsRun = edited || interrupted;+ const disabledOrAncestorDisabled =+ cellConfig.disabled || status === "disabled-transitively";+ const needsRun =+ edited || interrupted || (staleInputs && !disabledOrAncestorDisabled);const loading = status === "running" || status === "queued";const outputStale = outputIsStale(- { status, output, runStartTimestamp, interrupted },+ { status, output, runStartTimestamp, interrupted, staleInputs },edited,);// console output is cleared immediately on run, so check for queued instead// of loading to determine stalenessconst consoleOutputStale =- (status === "queued" || edited || status === "stale") && !interrupted;+ (status === "queued" || edited || staleInputs) && !interrupted;const editing = mode === "edit";// Performs side-effects that must run whenever the cell is run, but doesn't@@ -277,7 +282,7 @@ const CellComponent = ("has-error": errored,stopped: stopped,disabled: cellConfig.disabled,- stale: status === "stale" || status === "disabled-transitively",+ stale: status === "disabled-transitively",});const HTMLId = HTMLCellId.create(cellId);@@ -374,7 +379,7 @@ const CellComponent = (const cellTitle = () => {if (cellConfig.disabled) {return "This cell is disabled";- } else if (status === "stale" || status === "disabled-transitively") {+ } else if (status === "disabled-transitively") {return "This cell has a disabled ancestor";} else {return undefined;@@ -442,6 +447,7 @@ const CellComponent = (<div className="shoulder-right"><CellStatusComponentstatus={status}+ staleInputs={staleInputs}interrupted={interrupted}editing={editing}edited={edited}diff --git a/frontend/src/components/editor/cell/CellStatus.tsx b/frontend/src/components/editor/cell/CellStatus.tsxindex cb96d7cf8f..ba73934a6f 100644--- a/frontend/src/components/editor/cell/CellStatus.tsx+++ b/frontend/src/components/editor/cell/CellStatus.tsx@@ -22,6 +22,7 @@ export interface CellStatusComponentPropsediting: boolean;edited: boolean;disabled: boolean;+ staleInputs: boolean;elapsedTime: number | null;}@@ -29,6 +30,7 @@ export const CellStatusComponent: React.FC<CellStatusComponentProps> = ({editing,status,disabled,+ staleInputs,edited,interrupted,elapsedTime,@@ -44,7 +46,7 @@ export const CellStatusComponent: React.FC<CellStatusComponentProps> = ({return null;}// stale and disabled by self- if (disabled && status === "stale") {+ if (disabled && staleInputs) {return (<Tooltipcontent={"This cell is stale, but it's disabled and can't be run"}@@ -80,7 +82,7 @@ export const CellStatusComponent: React.FC<CellStatusComponentProps> = ({}// disabled from parent- if (status === "disabled-transitively") {+ if (!staleInputs && status === "disabled-transitively") {return (<Tooltipcontent={"An ancestor of this cell is disabled, so it can't be run"}@@ -101,7 +103,7 @@ export const CellStatusComponent: React.FC<CellStatusComponentProps> = ({}// stale from parent being disabled- if (status === "stale") {+ if (staleInputs && status === "disabled-transitively") {return (<Tooltipcontent={@@ -156,7 +158,7 @@ export const CellStatusComponent: React.FC<CellStatusComponentProps> = ({}// outdated- if (edited || interrupted) {+ if (edited || interrupted || staleInputs) {const elapsedTimeStr = formatElapsedTime(elapsedTime);const title = interrupted? "This cell was interrupted when it was last run"diff --git a/frontend/src/components/editor/cell/RunButton.tsx b/frontend/src/components/editor/cell/RunButton.tsxindex 7e4f5a7d77..96dc8c8a32 100644--- a/frontend/src/components/editor/cell/RunButton.tsx+++ b/frontend/src/components/editor/cell/RunButton.tsx@@ -35,8 +35,7 @@ export const RunButton = (props: {}): JSX.Element => {const { onClick, appClosed, needsRun, status, config, edited } = props;- const blockedStatus =- status === "stale" || status === "disabled-transitively";+ const blockedStatus = status === "disabled-transitively";const loading = status === "running" || status === "queued";const inactive =appClosed || loading || (!config.disabled && blockedStatus && !edited);diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsxindex 1854c5ab80..7090f1ccf8 100644--- a/frontend/src/components/editor/renderers/CellArray.tsx+++ b/frontend/src/components/editor/renderers/CellArray.tsx@@ -117,6 +117,7 @@ export const CellArray: React.FC<CellArrayProps> = ({interrupted={cell.interrupted}errored={cell.errored}stopped={cell.stopped}+ staleInputs={cell.staleInputs}runStartTimestamp={cell.runStartTimestamp}runElapsedTimeMs={cell.runElapsedTimeMs}serializedEditorState={cell.serializedEditorState}diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsxindex f6984a316a..1bdbfe3d61 100644--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx@@ -59,6 +59,7 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({mode={mode}runStartTimestamp={cell.runStartTimestamp}interrupted={cell.interrupted}+ staleInputs={cell.staleInputs}/>))}{canShowCode && (@@ -94,6 +95,7 @@ interface VerticalCellProps| "stopped"| "errored"| "interrupted"+ | "staleInputs"| "runStartTimestamp"> {cellId: CellId;@@ -112,6 +114,7 @@ const VerticalCell = memo(errored,config,interrupted,+ staleInputs,runStartTimestamp,code,showCode,@@ -125,6 +128,7 @@ const VerticalCell = memo(output,interrupted,runStartTimestamp,+ staleInputs,},false,);diff --git a/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap b/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snapindex bb0be25725..1150eabb63 100644--- a/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap+++ b/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap@@ -17,6 +17,7 @@ exports[`cell reducer > can initialize stdin 1`] = `"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "idle","stopped": false,}@@ -39,6 +40,7 @@ exports[`cell reducer > can initialize stdin 2`] = `"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "idle","stopped": false,}@@ -61,6 +63,7 @@ exports[`cell reducer > can initialize stdin 3`] = `"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "queued","stopped": false,}@@ -83,6 +86,7 @@ exports[`cell reducer > can initialize stdin 4`] = `"runElapsedTimeMs": null,"runStartTimestamp": 20,"serializedEditorState": null,+ "staleInputs": false,"status": "running","stopped": false,}@@ -112,6 +116,7 @@ exports[`cell reducer > can initialize stdin 5`] = `"runElapsedTimeMs": null,"runStartTimestamp": 20,"serializedEditorState": null,+ "staleInputs": false,"status": "running","stopped": false,}@@ -141,6 +146,7 @@ exports[`cell reducer > can initialize stdin 6`] = `"runElapsedTimeMs": null,"runStartTimestamp": 20,"serializedEditorState": null,+ "staleInputs": false,"status": "running","stopped": false,}@@ -176,6 +182,7 @@ exports[`cell reducer > can initialize stdin 7`] = `"runElapsedTimeMs": null,"runStartTimestamp": 20,"serializedEditorState": null,+ "staleInputs": false,"status": "running","stopped": false,}@@ -212,6 +219,7 @@ exports[`cell reducer > can initialize stdin 8`] = `"runElapsedTimeMs": null,"runStartTimestamp": 20,"serializedEditorState": null,+ "staleInputs": false,"status": "running","stopped": false,}@@ -254,6 +262,7 @@ exports[`cell reducer > can initialize stdin 9`] = `"runElapsedTimeMs": null,"runStartTimestamp": 20,"serializedEditorState": null,+ "staleInputs": false,"status": "running","stopped": false,}@@ -276,6 +285,7 @@ exports[`cell reducer > can receive console when the cell is idle and will clear"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "idle","stopped": false,}@@ -305,6 +315,7 @@ exports[`cell reducer > can receive console when the cell is idle and will clear"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "idle","stopped": false,}@@ -334,6 +345,7 @@ exports[`cell reducer > can receive console when the cell is idle and will clear"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "queued","stopped": false,}@@ -356,6 +368,7 @@ exports[`cell reducer > can receive console when the cell is idle and will clear"runElapsedTimeMs": null,"runStartTimestamp": 20,"serializedEditorState": null,+ "staleInputs": false,"status": "running","stopped": false,}@@ -385,6 +398,7 @@ exports[`cell reducer > can receive console when the cell is idle and will clear"runElapsedTimeMs": 2000,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "idle","stopped": false,}@@ -407,6 +421,7 @@ exports[`cell reducer > can run a stale cell 1`] = `"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "queued","stopped": false,}@@ -429,7 +444,8 @@ exports[`cell reducer > can run a stale cell 2`] = `"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,- "status": "stale",+ "staleInputs": true,+ "status": "queued","stopped": false,}`;@@ -451,6 +467,7 @@ exports[`cell reducer > can run a stopped cell 1`] = `"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "queued","stopped": false,}@@ -473,6 +490,7 @@ exports[`cell reducer > can run a stopped cell 2`] = `"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "idle","stopped": false,}@@ -506,6 +524,7 @@ exports[`cell reducer > can run a stopped cell 3`] = `"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "idle","stopped": true,}@@ -539,6 +558,7 @@ exports[`cell reducer > can run a stopped cell 4`] = `"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "queued","stopped": true,}@@ -561,6 +581,7 @@ exports[`cell reducer > can run a stopped cell 5`] = `"runElapsedTimeMs": null,"runStartTimestamp": 40,"serializedEditorState": null,+ "staleInputs": false,"status": "running","stopped": false,}@@ -583,6 +604,7 @@ exports[`cell reducer > can run cell and receive cell messages 1`] = `"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "idle","stopped": false,}@@ -605,6 +627,7 @@ exports[`cell reducer > can run cell and receive cell messages 2`] = `"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "idle","stopped": false,}@@ -627,6 +650,7 @@ exports[`cell reducer > can run cell and receive cell messages 3`] = `"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "idle","stopped": false,}@@ -649,6 +673,7 @@ exports[`cell reducer > can run cell and receive cell messages 4`] = `"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "queued","stopped": false,}@@ -671,6 +696,7 @@ exports[`cell reducer > can run cell and receive cell messages 5`] = `"runElapsedTimeMs": null,"runStartTimestamp": 20,"serializedEditorState": null,+ "staleInputs": false,"status": "running","stopped": false,}@@ -700,6 +726,7 @@ exports[`cell reducer > can run cell and receive cell messages 6`] = `"runElapsedTimeMs": null,"runStartTimestamp": 20,"serializedEditorState": null,+ "staleInputs": false,"status": "running","stopped": false,}@@ -734,6 +761,7 @@ exports[`cell reducer > can run cell and receive cell messages 7`] = `"runElapsedTimeMs": 13000,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "idle","stopped": false,}@@ -769,6 +797,7 @@ import numpy","runElapsedTimeMs": 13000,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "idle","stopped": false,}@@ -803,6 +832,7 @@ exports[`cell reducer > can run cell and receive cell messages 9`] = `"runElapsedTimeMs": 13000,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "idle","stopped": false,}@@ -838,6 +868,7 @@ import numpy","runElapsedTimeMs": 13000,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "idle","stopped": false,}@@ -880,6 +911,7 @@ import numpy","runElapsedTimeMs": 11000,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "idle","stopped": false,}@@ -920,6 +952,7 @@ import numpy","runElapsedTimeMs": 11000,"runStartTimestamp": null,"serializedEditorState": null,+ "staleInputs": false,"status": "idle","stopped": false,}diff --git a/frontend/src/core/cells/__tests__/cell.test.ts b/frontend/src/core/cells/__tests__/cell.test.tsindex e0d38903ab..b462670710 100644--- a/frontend/src/core/cells/__tests__/cell.test.ts+++ b/frontend/src/core/cells/__tests__/cell.test.ts@@ -9,7 +9,6 @@ const STATUSES: CellStatus[] = ["queued","running","idle",- "stale","disabled-transitively",];@@ -30,6 +29,7 @@ describe("outputIsStale", () => {(status) => {const cell = {status: status,+ staleInputs: true,output: null,runStartTimestamp: null,interrupted: false,@@ -42,6 +42,7 @@ describe("outputIsStale", () => {it("should return true if the cell is loading", () => {const cell = {status: "running" as CellStatus,+ staleInputs: false,output: null,runStartTimestamp: null,interrupted: false,@@ -53,6 +54,7 @@ describe("outputIsStale", () => {it("should return false if the cell is running and output is received after run started", () => {const cell = {status: "running" as CellStatus,+ staleInputs: false,output: createOutput(),runStartTimestamp: (Date.now() - 1000) as Seconds, // Output received after run startedinterrupted: false,@@ -63,7 +65,8 @@ describe("outputIsStale", () => {it("should return true if the cell status is stale", () => {const cell = {- status: "stale" as CellStatus,+ status: "disabled-transitively" as CellStatus,+ staleInputs: true,output: null,runStartTimestamp: null,interrupted: false,@@ -75,6 +78,7 @@ describe("outputIsStale", () => {it("should return false if the cell is interrupted", () => {const cell = {status: "running" as CellStatus,+ staleInputs: false,output: null,runStartTimestamp: null,interrupted: true,@@ -86,6 +90,7 @@ describe("outputIsStale", () => {it("should return true if the cell is running and output is received before run started", () => {const cell = {status: "running" as CellStatus,+ staleInputs: false,output: createOutput(),runStartTimestamp: (Date.now() + 1000) as Seconds, // Output received before run startedinterrupted: false,@@ -97,6 +102,7 @@ describe("outputIsStale", () => {it("should return false if the cell is idle and output is received", () => {const cell = {status: "idle" as CellStatus,+ staleInputs: false,output: createOutput(),runStartTimestamp: null,interrupted: false,@@ -108,6 +114,7 @@ describe("outputIsStale", () => {it("should return true if the cell is queued", () => {const cell = {status: "queued" as CellStatus,+ staleInputs: false,output: null,runStartTimestamp: null,interrupted: false,@@ -119,6 +126,7 @@ describe("outputIsStale", () => {it("should return true if the cell is running but no output is received", () => {const cell = {status: "running" as CellStatus,+ staleInputs: false,output: null,runStartTimestamp: Date.now() as Seconds,interrupted: false,@@ -130,6 +138,7 @@ describe("outputIsStale", () => {it("should return false if the cell is idle and not edited", () => {const cell = {status: "idle" as CellStatus,+ staleInputs: false,output: null,runStartTimestamp: null,interrupted: false,@@ -142,6 +151,7 @@ describe("outputIsStale", () => {// We likely don't get in this state since before a cell is interrupted, it is run and we remove the edited stateconst cell = {status: "idle" as CellStatus,+ staleInputs: false,output: null,runStartTimestamp: null,interrupted: true,@@ -151,9 +161,9 @@ describe("outputIsStale", () => {});it("should return true if the cell is interrupted but has a stale status", () => {- // We likely don't get in this state since when a cell is interrupted, it's status is set to idleconst cell = {- status: "stale" as CellStatus,+ status: "disabled-transitively" as CellStatus,+ staleInputs: true,output: null,runStartTimestamp: null,interrupted: true,diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.tsindex 41d6abd04f..fe7546c9d5 100644--- a/frontend/src/core/cells/__tests__/cells.test.ts+++ b/frontend/src/core/cells/__tests__/cells.test.ts@@ -279,6 +279,7 @@ describe("cell reducer", () => {output: null,console: null,status: "queued",+ stale_inputs: null,timestamp: new Date(10).getTime() as Seconds,},});@@ -298,6 +299,7 @@ describe("cell reducer", () => {output: null,console: null,status: "running",+ stale_inputs: null,timestamp: new Date(20).getTime() as Seconds,},});@@ -322,6 +324,7 @@ describe("cell reducer", () => {timestamp: 0,},status: null,+ stale_inputs: null,timestamp: new Date(22).getTime() as Seconds,},});@@ -350,6 +353,7 @@ describe("cell reducer", () => {timestamp: 0,},status: "idle",+ stale_inputs: null,timestamp: new Date(33).getTime() as Seconds,},});@@ -411,6 +415,7 @@ describe("cell reducer", () => {output: null,console: null,status: "queued",+ stale_inputs: null,timestamp: new Date(40).getTime() as Seconds,},});@@ -424,6 +429,7 @@ describe("cell reducer", () => {output: null,console: null,status: "running",+ stale_inputs: null,timestamp: new Date(50).getTime() as Seconds,},});@@ -444,6 +450,7 @@ describe("cell reducer", () => {},console: null,status: "idle",+ stale_inputs: null,timestamp: new Date(61).getTime() as Seconds,},});@@ -472,6 +479,7 @@ describe("cell reducer", () => {output: null,console: null,status: "queued",+ stale_inputs: null,timestamp: new Date(40).getTime() as Seconds,},});@@ -485,6 +493,7 @@ describe("cell reducer", () => {output: null,console: null,status: "running",+ stale_inputs: null,timestamp: new Date(50).getTime() as Seconds,},});@@ -503,6 +512,7 @@ describe("cell reducer", () => {},console: null,status: "idle",+ stale_inputs: null,timestamp: new Date(61).getTime() as Seconds,},});@@ -548,6 +558,7 @@ describe("cell reducer", () => {output: null,console: null,status: "queued",+ stale_inputs: null,timestamp: new Date(10).getTime() as Seconds,},});@@ -566,12 +577,13 @@ describe("cell reducer", () => {cell_id: secondCell,output: null,console: null,- status: "stale",+ status: null,+ stale_inputs: true,timestamp: new Date(20).getTime() as Seconds,},});cell = cells[1];- expect(cell.status).toBe("stale");+ expect(cell.status).toBe("queued");expect(cell.lastCodeRun).toBe("mo.slider()");expect(cell.edited).toBe(false);expect(cell.runElapsedTimeMs).toBe(null);@@ -612,6 +624,7 @@ describe("cell reducer", () => {timestamp: 0,},status: "idle",+ stale_inputs: null,timestamp: new Date(33).getTime() as Seconds,},});@@ -677,6 +690,7 @@ describe("cell reducer", () => {output: null,console: null,status: "queued",+ stale_inputs: null,timestamp: new Date(10).getTime() as Seconds,},});@@ -698,6 +712,7 @@ describe("cell reducer", () => {output: null,console: null,status: "idle",+ stale_inputs: null,timestamp: new Date(20).getTime() as Seconds,},});@@ -723,6 +738,7 @@ describe("cell reducer", () => {},console: null,status: "idle",+ stale_inputs: null,timestamp: new Date(20).getTime() as Seconds,},});@@ -743,6 +759,7 @@ describe("cell reducer", () => {output: null,console: null,status: "queued",+ stale_inputs: null,timestamp: new Date(30).getTime() as Seconds,},});@@ -759,6 +776,7 @@ describe("cell reducer", () => {output: null,console: null,status: "running",+ stale_inputs: null,timestamp: new Date(40).getTime() as Seconds,},});@@ -812,6 +830,7 @@ describe("cell reducer", () => {output: null,console: null,status: "queued",+ stale_inputs: null,timestamp: new Date(10).getTime() as Seconds,},});@@ -827,6 +846,7 @@ describe("cell reducer", () => {output: null,console: null,status: "running",+ stale_inputs: null,timestamp: new Date(20).getTime() as Seconds,},});@@ -842,6 +862,7 @@ describe("cell reducer", () => {output: null,console: STDOUT,status: null,+ stale_inputs: null,timestamp: new Date(22).getTime() as Seconds,},});@@ -862,6 +883,7 @@ describe("cell reducer", () => {output: null,console: STD_IN_1,status: null,+ stale_inputs: null,timestamp: new Date(22).getTime() as Seconds,},});@@ -895,6 +917,7 @@ describe("cell reducer", () => {output: null,console: STD_IN_2,status: null,+ stale_inputs: null,timestamp: new Date(22).getTime() as Seconds,},});@@ -920,6 +943,7 @@ describe("cell reducer", () => {},console: null,status: "idle",+ stale_inputs: null,timestamp: new Date(61).getTime() as Seconds,},});@@ -960,6 +984,7 @@ describe("cell reducer", () => {output: null,console: [OLD_STDOUT],status: null,+ stale_inputs: null,timestamp: new Date(1).getTime() as Seconds,},});@@ -981,6 +1006,7 @@ describe("cell reducer", () => {output: null,console: null,status: "queued",+ stale_inputs: null,timestamp: new Date(10).getTime() as Seconds,},});@@ -997,6 +1023,7 @@ describe("cell reducer", () => {output: null,console: [], // Backend sends an empty array to clearustatus: "running",+ stale_inputs: null,timestamp: new Date(20).getTime() as Seconds,},});@@ -1013,6 +1040,7 @@ describe("cell reducer", () => {output: null,console: [STDOUT],status: "idle",+ stale_inputs: null,timestamp: new Date(22).getTime() as Seconds,},});diff --git a/frontend/src/core/cells/cell.ts b/frontend/src/core/cells/cell.tsindex 3e7492a9c1..db50597d23 100644--- a/frontend/src/core/cells/cell.ts+++ b/frontend/src/core/cells/cell.ts@@ -50,9 +50,6 @@ export function transitionCell(break;case null:break;- case "stale":- // Everything should already be up to date from prepareCellForExecution- break;case "disabled-transitively":// Everything should already be up to date from prepareCellForExecutionbreak;@@ -61,6 +58,7 @@ export function transitionCell(}nextCell.output = message.output ?? nextCell.output;+ nextCell.staleInputs = message.stale_inputs ?? nextCell.staleInputs;nextCell.status = message.status ?? nextCell.status;let didInterruptFromThisMessage = false;@@ -144,23 +142,23 @@ export function prepareCellForExecution(}/**- * A cell is stale if it has been edited, is loading, or has errored.+ * A cell's output is stale if it has been edited, is loading, or has errored.*/export function outputIsStale(cell: Pick<CellRuntimeState,- "status" | "output" | "runStartTimestamp" | "interrupted"+ "status" | "output" | "runStartTimestamp" | "interrupted" | "staleInputs">,edited: boolean,): boolean {- const { status, output, runStartTimestamp, interrupted } = cell;+ const { status, output, runStartTimestamp, interrupted, staleInputs } = cell;- // If interrupted, the cell is not stale+ // If interrupted, the output is not staleif (interrupted) {return false;}- // If edited, the cell is stale+ // If edited, the cell's output is staleif (edited) {return true;}@@ -180,5 +178,5 @@ export function outputIsStale(return true;}- return status === "stale";+ return staleInputs;}diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex c03fec6d66..92e205b038 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -841,10 +841,21 @@ export function enabledCellIds(state: NotebookState) {.filter((cell) => !cell.config.disabled);}+/**+ * Cells that are stale and can be run.+ */export function staleCellIds(state: NotebookState) {const { cellIds, cellData, cellRuntime } = state;return cellIds.filter(- (cellId) => cellData[cellId].edited || cellRuntime[cellId].interrupted,+ (cellId) =>+ cellData[cellId].edited ||+ cellRuntime[cellId].interrupted ||+ (cellRuntime[cellId].staleInputs &&+ // if a cell is disabled, it can't be run ...+ !(+ cellRuntime[cellId].status === "disabled-transitively" ||+ cellData[cellId].config.disabled+ )),);}diff --git a/frontend/src/core/cells/types.ts b/frontend/src/core/cells/types.tsindex 5f2443c977..086a429195 100644--- a/frontend/src/core/cells/types.ts+++ b/frontend/src/core/cells/types.ts@@ -12,14 +12,12 @@ import { Milliseconds, Seconds } from "@/utils/time";* queued: queued by the kernel.* running: currently executing.* idle: not running.- * stale: stale, likely because the cell was disabled or an ancestor was disabled.* disabled-transitively: disabled because an ancestor was disabled.*/export type CellStatus =| "queued"| "running"| "idle"- | "stale"| "disabled-transitively";/**@@ -51,6 +49,7 @@ export function createCellRuntimeState(): CellRuntimeState {output: null,consoleOutputs: [],status: "idle",+ staleInputs: false,interrupted: false,errored: false,stopped: false,@@ -88,6 +87,8 @@ export interface CellRuntimeState {consoleOutputs: OutputMessage[];/** current status of the cell */status: CellStatus;+ /** whether the cell has stale inputs*/+ staleInputs: boolean;/** whether this cell has been interrupted since its last run */interrupted: boolean;/** whether this cell was stopped with mo.stop */diff --git a/frontend/src/core/config/__tests__/config-schema.test.ts b/frontend/src/core/config/__tests__/config-schema.test.tsindex 6219485796..7e027dfa1d 100644--- a/frontend/src/core/config/__tests__/config-schema.test.ts+++ b/frontend/src/core/config/__tests__/config-schema.test.ts@@ -37,7 +37,7 @@ test("default UserConfig - empty", () => {},"runtime": {"auto_instantiate": true,- "auto_reload": false,+ "auto_reload": "off",},"save": {"autosave": "after_delay",@@ -82,7 +82,7 @@ test("default UserConfig - one level", () => {},"runtime": {"auto_instantiate": true,- "auto_reload": false,+ "auto_reload": "off",},"save": {"autosave": "after_delay",diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex 06687b817d..64201c9247 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -53,7 +53,7 @@ export const UserConfigSchema = zruntime: z.object({auto_instantiate: z.boolean().default(true),- auto_reload: z.boolean().default(false),+ auto_reload: z.enum(["off", "detect", "autorun"]).default("off"),}).default({}),display: zdiff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.tsindex 9efdf89102..4af5cb9ae1 100644--- a/frontend/src/core/kernel/messages.ts+++ b/frontend/src/core/kernel/messages.ts@@ -101,6 +101,10 @@ export interface CellMessage {* means no transition in status.*/status: CellStatus | null;+ /**+ * Transition in staleness.+ */+ stale_inputs: boolean | null;/*** Timestamp in seconds since epoch, when the message was sent*/diff --git a/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap b/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snapnew file mode 100644index 0000000000..c256efbb3a--- /dev/null+++ b/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap@@ -0,0 +1,113 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`download-html > should construct html correctly 1`] = `+"<!doctype html>+<html>+ <head>+ <base href="/" />++ <meta charset="utf-8" />+ <link+ rel="icon"+ href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/favicon.ico"+ crossorigin="anonymous"+ />+ <link+ rel="preload"+ href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/gradient-6c6e9bb3.png"+ as="image"+ crossorigin="anonymous"+ />+ <link+ rel="preload"+ href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/noise-b5c8172e.png"+ as="image"+ crossorigin="anonymous"+ />++ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <meta name="theme-color" content="#000000" />+ <meta name="description" content="a marimo app" />+ <link+ rel="apple-touch-icon"+ href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/apple-touch-icon.png"+ crossorigin="anonymous"+ />+ <link+ rel="manifest"+ href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/manifest.json"+ crossorigin="anonymous"+ />+ <script data-marimo="true">+ function __resizeIframe(obj) {+ // Resize the iframe to the height of the content+ obj.style.height =+ obj.contentWindow.document.documentElement.scrollHeight + "px";++ // Resize the iframe when the content changes+ const resizeObserver = new ResizeObserver((entries) => {+ obj.style.height =+ obj.contentWindow.document.documentElement.scrollHeight + "px";+ });+ resizeObserver.observe(obj.contentWindow.document.body);+ }+ </script>++ <link rel="preconnect" href="https://fonts.googleapis.com" />+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="" />+ <link+ href="https://fonts.googleapis.com/css2?family=Fira+Mono:wght@400;500;700&family=Lora&family=PT+Sans:wght@400;700&display=swap"+ rel="stylesheet"+ />+ </head>++ <body>+ <div id="root"></div>+ <marimo-mode data-mode="read" hidden=""></marimo-mode>+ <marimo-filename hidden="">app.py</marimo-filename>+ <marimo-version data-version="0.1.44" hidden=""></marimo-version>+ <marimo-user-config+ data-config='{"display": {"theme": "light"}, "keymap": {"preset": "default"}, "save": {"autosave": "after_delay", "format_on_save": true, "autosave_delay": 1000}, "server": {"browser": "default"}, "experimental": {"layouts": true, "theming": true}, "runtime": {"auto_instantiate": true}, "completion": {"activate_on_typing": true, "copilot": true}}'+ hidden=""+ ></marimo-user-config>+ <marimo-app-config+ data-config='{"width": "full", "layout_file": null}'+ hidden=""+ ></marimo-app-config>+ <script data-marimo="true">+ window.__MARIMO_STATIC__ = {};+ window.__MARIMO_STATIC__.version = "0.1.44";+ window.__MARIMO_STATIC__.notebookState = {+ cellIds: ["1"],+ cellData: {+ 1: "JTdCJTIyaWQlMjIlM0ElMjIxJTIyJTJDJTIyY29uZmlnJTIyJTNBJTdCJTIyaGlkZV9jb2RlJTIyJTNBdHJ1ZSU3RCUyQyUyMm5hbWUlMjIlM0ElMjJjZWxsJTIyJTJDJTIyY29kZSUyMiUzQSUyMmNvZGUlMjIlMkMlMjJlZGl0ZWQlMjIlM0FmYWxzZSUyQyUyMmxhc3RDb2RlUnVuJTIyJTNBbnVsbCUyQyUyMnNlcmlhbGl6ZWRFZGl0b3JTdGF0ZSUyMiUzQW51bGwlN0Q=",+ },+ cellRuntime: {+ 1: "JTdCJTIyb3V0bGluZSUyMiUzQW51bGwlMkMlMjJvdXRwdXQlMjIlM0FudWxsJTJDJTIyY29uc29sZU91dHB1dHMlMjIlM0ElNUIlNUQlMkMlMjJzdGF0dXMlMjIlM0ElMjJpZGxlJTIyJTJDJTIyc3RhbGVJbnB1dHMlMjIlM0FmYWxzZSUyQyUyMmludGVycnVwdGVkJTIyJTNBZmFsc2UlMkMlMjJlcnJvcmVkJTIyJTNBZmFsc2UlMkMlMjJzdG9wcGVkJTIyJTNBZmFsc2UlMkMlMjJydW5FbGFwc2VkVGltZU1zJTIyJTNBbnVsbCUyQyUyMnJ1blN0YXJ0VGltZXN0YW1wJTIyJTNBbnVsbCUyQyUyMmRlYnVnZ2VyQWN0aXZlJTIyJTNBZmFsc2UlN0Q=",+ },+ };+ window.__MARIMO_STATIC__.assetUrl =+ "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";+ window.__MARIMO_STATIC__.files = {+ "/@file/note.txt": { base64: "data:text/plain;base64,bm90ZQo=" },+ };+ </script>++ <marimo-code hidden="">+ import%20marimo%20as%20mo%0A%0Amo.html('%3Ch1%3Ehello%3C%2Fh1%3E')+ </marimo-code>++ <script+ type="module"+ crossorigin="anonymous"+ src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index-2e140915.js"+ ></script>+ <link+ rel="stylesheet"+ href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index-116d8088.css"+ crossorigin="anonymous"+ />+ </body>+</html>+"+`;diff --git a/frontend/src/stories/cell-status.stories.tsx b/frontend/src/stories/cell-status.stories.tsxindex b3c5682969..c07fef7053 100644--- a/frontend/src/stories/cell-status.stories.tsx+++ b/frontend/src/stories/cell-status.stories.tsx@@ -105,7 +105,8 @@ DisabledTransitivelyAndEdited.args = {export const Stale = Template.bind({});Stale.args = {editing: true,- status: "stale",+ status: "disabled-transitively",+ staleInputs: true,edited: false,interrupted: false,disabled: false,@@ -115,7 +116,8 @@ Stale.args = {export const StaleAndDisabled = Template.bind({});StaleAndDisabled.args = {editing: true,- status: "stale",+ status: "disabled-transitively",+ staleInputs: true,edited: false,interrupted: false,disabled: true,@@ -125,8 +127,8 @@ StaleAndDisabled.args = {export const EditedStaleAndDisabled = Template.bind({});EditedStaleAndDisabled.args = {editing: true,- status: "stale",- edited: true,+ status: "disabled-transitively",+ staleInputs: true,interrupted: false,disabled: true,elapsedTime: null,@@ -135,7 +137,7 @@ EditedStaleAndDisabled.args = {export const EditedAndStale = Template.bind({});EditedAndStale.args = {editing: true,- status: "stale",+ status: "disabled-transitively",edited: true,interrupted: false,disabled: false,diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsxindex 4b3f3e9eaa..24835c06c6 100644--- a/frontend/src/stories/cell.stories.tsx+++ b/frontend/src/stories/cell.stories.tsx@@ -27,6 +27,7 @@ const props: CellProps = {interrupted: false,errored: false,stopped: false,+ staleInputs: false,updateCellCode: Logger.log,prepareForRun: Logger.log,runStartTimestamp: 0 as Seconds,@@ -66,7 +67,7 @@ const props: CellProps = {},runtime: {auto_instantiate: true,- auto_reload: false,+ auto_reload: "off",},keymap: {preset: "default",@@ -241,7 +242,8 @@ export const StaleStatus: Story = {<Cell{...props}runElapsedTimeMs={20 as Milliseconds}- status="stale"+ status="disabled-transitively"+ staleInputs={true}output={{channel: "output",data: "This data is stale because a parent is disabled",@@ -261,7 +263,8 @@ export const StaleAndEditedStatus: Story = {<Cell{...props}runElapsedTimeMs={20 as Milliseconds}- status="stale"+ status="disabled-transitively"+ staleInputs={true}output={{channel: "output",data: "This data is stale because a parent is disabled, but this cell has been edited since.",@@ -284,7 +287,8 @@ export const DisabledAndStaleStatus: Story = {config={{disabled: true,}}- status="stale"+ status="disabled-transitively"+ staleInputs={true}output={{channel: "output",data: "<span class='markdown'><h1>Layout</h1>\n<p><code>marimo</code> provides functions to help you lay out your output, such as\nin rows and columns, accordions, tabs, and callouts. This tutorial\nshows some examples.</p></span>",diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex 6a0dfa0636..0e8d8a6e79 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -5,17 +5,18 @@ import dataclassesimport inspectfrom typing import TYPE_CHECKING, Any, Callable, Literal, Mapping, Optional-from marimo._ast.visitor import Name, VariableData+from marimo._ast.visitor import ImportData, Name, VariableDatafrom marimo._utils.deep_merge import deep_mergeCellId_t = strif TYPE_CHECKING:import ast- from collections.abc import Awaitable+ from collections.abc import Awaitable, Iterablefrom types import CodeTypefrom marimo._ast.app import InternalApp+ from marimo._messaging.types import Streamfrom marimo._output.hypertext import Html@@ -59,11 +60,8 @@ CellConfigKeys = frozenset(# idle: cell has run with latest inputs# queued: cell is queued to run# running: cell is running-# stale: cell hasn't run with latest inputs, and can't run (disabled)# disabled-transitively: cell is disabled because a parent is disabled-CellStatusType = Literal[- "idle", "queued", "running", "stale", "disabled-transitively"-]+CellStatusType = Literal["idle", "queued", "running", "disabled-transitively"]@dataclasses.dataclass@@ -77,6 +75,11 @@ def _is_coroutine(code: Optional[CodeType]) -> bool:return inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE+class CellStaleState:+ state: bool = False++@dataclasses.dataclass(frozen=True)class CellImpl:# hash of code@@ -98,6 +101,7 @@ class CellImpl:config: CellConfig = dataclasses.field(default_factory=CellConfig)# status: status, inferred at runtime_status: CellStatus = dataclasses.field(default_factory=CellStatus)+ _stale: CellStaleState = dataclasses.field(default_factory=CellStaleState)def configure(self, update: dict[str, Any] | CellConfig) -> CellImpl:"""Update the cel config.@@ -113,39 +117,53 @@ class CellImpl:@propertydef stale(self) -> bool:- return self.status == "stale"+ return self._stale.state@propertydef disabled_transitively(self) -> bool:return self.status == "disabled-transitively"@property- def imported_modules(self) -> set[Name]:- """Return a set of the modules imported by this cell."""+ def imports(self) -> Iterable[ImportData]:+ """Return a set of the namespaces imported by this cell."""+ return [+ data.import_data+ for _, data in self.variable_data.items()+ if data.import_data is not None+ ]++ @property+ def imported_namespaces(self) -> set[Name]:+ """Return a set of the namespaces imported by this cell."""return set(- data.module+ data.import_data.module.split(".")[0]for _, data in self.variable_data.items()- if data.module is not None+ if data.import_data is not None)- def module_to_variable(self, module: str) -> Name | None:- """Returns the variable name corresponding to an imported module+ def namespace_to_variable(self, namespace: str) -> Name | None:+ """Returns the variable name corresponding to an imported namespaceRelevant for imports "as" imports, egimport matplotlib.pyplot as plt- In this case the module is "matplotlib" but the name is "plt".+ In this case the namespace is "matplotlib" but the name is "plt"."""for name, data in self.variable_data.items():- if data.module == module:+ if (+ data.import_data is not None+ and data.import_data.namespace == namespace+ ):return namereturn Nonedef is_coroutine(self) -> bool:return _is_coroutine(self.body) or _is_coroutine(self.last_expr)- def set_status(self, status: CellStatusType) -> None:+ def set_status(+ self, status: CellStatusType, stream: Stream | None = None+ ) -> None:from marimo._messaging.ops import CellOpfrom marimo._runtime.context import (ContextNotInitializedError,@@ -159,7 +177,17 @@ class CellImpl:returnassert self.cell_id is not None- CellOp.broadcast_status(cell_id=self.cell_id, status=status)+ CellOp.broadcast_status(+ cell_id=self.cell_id, status=status, stream=stream+ )++ def set_stale(self, stale: bool, stream: Stream | None = None) -> None:+ from marimo._messaging.ops import CellOp++ self._stale.state = stale+ CellOp.broadcast_stale(+ cell_id=self.cell_id, stale=stale, stream=stream+ )@dataclasses.dataclassdiff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.pyindex f55076d0ac..7ad19d614a 100644--- a/marimo/_ast/visitor.py+++ b/marimo/_ast/visitor.py@@ -10,13 +10,27 @@ from uuid import uuid4Name = str+@dataclass+class ImportData:+ # full module name+ # e.g., a.b.c.+ module: str+ # fully qualified import symbol:+ # import a.b => symbol == None+ # from a.b import c => symbol == a.b.c+ imported_symbol: Optional[str] = None+ import_level: Optional[int] = None++ def __post_init__(self) -> None:+ self.namespace = self.module.split(".")[0]++@dataclassclass VariableData:kind: Literal["function", "class", "import", "variable"] = "variable"# For kind == import- module: Optional[str] = None- import_level: Optional[int] = None+ import_data: Optional[ImportData] = Nonedef is_local(name: str) -> bool:@@ -373,30 +387,35 @@ class ScopedVisitor(ast.NodeVisitor):for name in node.names:self.block_stack[-1].global_names.add(name)- # TODO(akshayka): can we find a way around tracking imports as state- # that needs to be tracked?- # Import and ImportFrom statements have symbol names in alias nodes- def visit_alias(self, node: ast.alias) -> None:- """Visiting names in import statements"""- name = self._get_alias_name(node)- # Extract module name- # - import a.b.c as d: module name a is different from the alias name d- # - import a.b.c: module name a is equal to the alias name a- module = node.name.split(".")[0] if node.asname is not None else name- self._define(name, VariableData(kind="import", module=module))- self.generic_visit(node)+ def visit_Import(self, node: ast.Import) -> None:+ for alias_node in node.names:+ variable_name = self._get_alias_name(alias_node)+ self._define(+ variable_name,+ VariableData(+ kind="import",+ import_data=ImportData(+ module=alias_node.name, imported_symbol=None+ ),+ ),+ )def visit_ImportFrom(self, node: ast.ImportFrom) -> None:- # module should not be None here, but appease the type checker- module = node.module.split(".")[0] if node.module is not None else None- imported_names = [self._get_alias_name(alias) for alias in node.names]+ module = node.module if node.module is not None else ""# we don't recurse into the alias nodes, since we define the# aliases here- for name in imported_names:+ for alias_node in node.names:+ variable_name = self._get_alias_name(alias_node)+ original_name = alias_node.nameself._define(- name,+ variable_name,VariableData(- kind="import", module=module, import_level=node.level+ kind="import",+ import_data=ImportData(+ module=module,+ imported_symbol=module + "." + original_name,+ import_level=node.level,+ ),),)diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex 0b4db23c83..2fd5478125 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -70,12 +70,13 @@ class RuntimeConfig(TypedDict):run on startup. This only applies when editing a notebook,and not when running as an application.The default is `True`.- - `auto_reload`: if `True`, modified modules will be automatically reloaded- before cell execution; similar to IPython's %autoreload 2.+ - `auto_reload`: if `detect`, cells importing modified modules will marked+ as stale; if `autorun`, affected cells will be automatically run. similar+ to IPython's %autoreload extension but with more code intelligence."""auto_instantiate: bool- auto_reload: bool+ auto_reload: Literal["off", "detect", "autorun"]@mddoc@@ -180,7 +181,7 @@ DEFAULT_CONFIG: MarimoConfig = {},"formatting": {"line_length": 79},"keymap": {"preset": "default"},- "runtime": {"auto_instantiate": True, "auto_reload": False},+ "runtime": {"auto_instantiate": True, "auto_reload": "off"},"save": {"autosave": "after_delay","autosave_delay": 1000,@@ -200,13 +201,24 @@ def merge_config(config: MarimoConfig, new_config: MarimoConfig) -> MarimoConfig:"""Merge a user configuration with a new configuration."""- return cast(+ merged = cast(MarimoConfig,deep_merge(cast(Dict[Any, Any], config), cast(Dict[Any, Any], new_config)),)+ # Patches for backward compatibility+ if (+ merged["runtime"]["auto_reload"] is False # type:ignore[comparison-overlap]+ ):+ merged["runtime"]["auto_reload"] = "off"+ if (+ merged["runtime"]["auto_reload"] is True # type:ignore[comparison-overlap]+ ):+ merged["runtime"]["auto_reload"] = "detect"+ return merged+def _deep_copy(obj: Any) -> Any:if isinstance(obj, dict):diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex f30f39636d..cd123f9976 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -62,9 +62,11 @@ class CellOp(Op):A CellOp's data has three optional fields:- output - a CellOutput- console - a CellOutput (console msg to append), or a list of CellOutputs- status - execution status+ output - a CellOutput+ console - a CellOutput (console msg to append), or a list of+ CellOutputs+ status - execution status+ stale_inputs - whether the cell has stale inputs (variables, modules, ...)Omitting a field means that its value should be unchanged!@@ -78,6 +80,7 @@ class CellOp(Op):output: Optional[CellOutput] = Noneconsole: Optional[Union[CellOutput, List[CellOutput]]] = Nonestatus: Optional[CellStatusType] = None+ stale_inputs: Optional[bool] = Nonetimestamp: float = field(default_factory=lambda: time.time())@staticmethod@@ -123,6 +126,7 @@ class CellOp(Op):data: str,cell_id: Optional[CellId_t],status: Optional[CellStatusType],+ stream: Stream | None = None,) -> None:mimetype, data = CellOp.maybe_truncate_output(mimetype, data)cell_id = (@@ -137,12 +141,13 @@ class CellOp(Op):data=data,),status=status,- ).broadcast()+ ).broadcast(stream=stream)@staticmethoddef broadcast_empty_output(cell_id: Optional[CellId_t],status: Optional[CellStatusType],+ stream: Stream | None = None,) -> None:cell_id = (cell_id if cell_id is not None else get_context().stream.cell_id@@ -156,7 +161,7 @@ class CellOp(Op):data="",),status=status,- ).broadcast()+ ).broadcast(stream=stream)@staticmethoddef broadcast_console_output(@@ -165,6 +170,7 @@ class CellOp(Op):data: str,cell_id: Optional[CellId_t],status: Optional[CellStatusType],+ stream: Stream | None = None,) -> None:mimetype, data = CellOp.maybe_truncate_output(mimetype, data)cell_id = (@@ -179,15 +185,19 @@ class CellOp(Op):data=data,),status=status,- ).broadcast()+ ).broadcast(stream=stream)@staticmethod- def broadcast_status(cell_id: CellId_t, status: CellStatusType) -> None:+ def broadcast_status(+ cell_id: CellId_t, status: CellStatusType, stream: Stream | None = None+ ) -> None:if status != "running":CellOp(cell_id=cell_id, status=status).broadcast()else:# Console gets cleared on "running"- CellOp(cell_id=cell_id, console=[], status=status).broadcast()+ CellOp(cell_id=cell_id, console=[], status=status).broadcast(+ stream=stream+ )@staticmethoddef broadcast_error(@@ -208,6 +218,12 @@ class CellOp(Op):status=status,).broadcast()+ @staticmethod+ def broadcast_stale(+ cell_id: CellId_t, stale: bool, stream: Stream | None = None+ ) -> None:+ CellOp(cell_id=cell_id, stale_inputs=stale).broadcast(stream)+@dataclassclass HumanReadableStatus(Op):diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.pyindex 8d33525c09..73905da8ad 100644--- a/marimo/_pyodide/pyodide_session.py+++ b/marimo/_pyodide/pyodide_session.py@@ -28,6 +28,7 @@ from marimo._runtime.requests import (CompletionRequest,ControlRequest,CreationRequest,+ ExecuteStaleRequest,ExecutionRequest,SerializedQueryParams,SetUIElementValueRequest,@@ -380,6 +381,9 @@ def launch_pyodide_kernel(stdout=stdout,stderr=stderr,stdin=stdin,+ execute_stale_cells_callback=lambda: control_queue.put_nowait(+ ExecuteStaleRequest()+ ),input_override=input_override,debugger_override=debugger,user_config=user_config,diff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.pyindex 57c67ca8b3..15441a07c7 100644--- a/marimo/_runtime/dataflow.py+++ b/marimo/_runtime/dataflow.py@@ -171,8 +171,7 @@ class DirectedGraph:for cid in transitive_closure(self, set([cell_id])) - set([cell_id]):cell = self.cells[cid]- if not cell.stale:- cell.set_status(status="disabled-transitively")+ cell.set_status(status="disabled-transitively")def enable_cell(self, cell_id: CellId_t) -> set[CellId_t]:"""diff --git a/marimo/_runtime/packages/module_registry.py b/marimo/_runtime/packages/module_registry.pyindex ab2396fd69..b36e440428 100644--- a/marimo/_runtime/packages/module_registry.py+++ b/marimo/_runtime/packages/module_registry.py@@ -37,7 +37,7 @@ class ModuleRegistry:def defining_cell(self, module_name: str) -> CellId_t | None:"""Get the cell id of the cell importing module_name"""for cell_id, cell in self.graph.cells.items():- if cell.module_to_variable(module_name) is not None:+ if cell.namespace_to_variable(module_name) is not None:return cell_idreturn None@@ -46,7 +46,7 @@ class ModuleRegistry:return set(modfor cell in self.graph.cells.values()- for mod in cell.imported_modules+ for mod in cell.imported_namespaces)def missing_modules(self) -> set[str]:diff --git a/marimo/_runtime/reload/__init__.py b/marimo/_runtime/reload/__init__.pynew file mode 100644index 0000000000..be52407b50--- /dev/null+++ b/marimo/_runtime/reload/__init__.py@@ -0,0 +1 @@+# Copyright 2024 Marimo. All rights reserved.diff --git a/marimo/_runtime/autoreload.py b/marimo/_runtime/reload/autoreload.pysimilarity index 98%rename from marimo/_runtime/autoreload.pyrename to marimo/_runtime/reload/autoreload.pyindex 4133b76980..82930253a1 100644--- a/marimo/_runtime/autoreload.py+++ b/marimo/_runtime/reload/autoreload.py@@ -94,13 +94,14 @@ class ModuleReloader:def check(self, modules: dict[str, types.ModuleType], reload: bool- ) -> None:+ ) -> set[types.ModuleType]:"""Check timestamps of modules, optionally reload them.Also patches existing objects with hot-reloaded ones."""# materialize the module keys, since we'll be reloading while iterating+ modified_modules: set[types.ModuleType] = set()for modname in list(modules.keys()):m = modules.get(modname, None)if m is None:@@ -122,6 +123,7 @@ class ModuleReloader:continueself.modules_mtimes[modname] = pymtime+ modified_modules.add(m)# If we've reached this point, we should try to reload the moduleif reload:@@ -136,6 +138,7 @@ class ModuleReloader:msg.format(modname, traceback.format_exc(10)),)self.failed[py_filename] = pymtime+ return modified_modulesdef update_function(old: object, new: object) -> None:diff --git a/marimo/_runtime/reload/module_watcher.py b/marimo/_runtime/reload/module_watcher.pynew file mode 100644index 0000000000..fc6d45b2d5--- /dev/null+++ b/marimo/_runtime/reload/module_watcher.py@@ -0,0 +1,180 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import itertools+import sys+import threading+import time+from modulefinder import ModuleFinder+from typing import TYPE_CHECKING, Callable, Literal++from marimo._ast.cell import CellId_t, CellImpl+from marimo._messaging.types import Stream+from marimo._runtime import dataflow+from marimo._runtime.reload.autoreload import ModuleReloader++if TYPE_CHECKING:+ import types+++def _modules_imported_by_cell(cell: CellImpl) -> set[str]:+ """Get the modules imported by a cell"""+ modules = set()+ for import_data in cell.imports:+ if import_data.module in sys.modules:+ modules.add(import_data.module)+ if import_data.imported_symbol in sys.modules:+ # The imported symbol may or may not be a module, which+ # is why we check if it's in sys.modules+ #+ # e.g., from a import b+ #+ # a.b could be a module, but it could also be a function, ...+ modules.add(import_data.imported_symbol)+ return modules+++def _depends_on(+ src_module: types.ModuleType,+ target_filenames: set[str],+ failed_filenames: set[str],+) -> bool:+ """Returns whether src_module depends on any of target_filenames"""+ if not hasattr(src_module, "__file__") or src_module.__file__ is None:+ return False++ if src_module.__file__ in failed_filenames:+ return False++ finder = ModuleFinder()+ try:+ finder.run_script(src_module.__file__)+ except SyntaxError:+ # user introduced a syntax error, maybe; don't+ # exclude this module from future searches+ return True+ except Exception:+ # some modules like numpy fail when called with run_script;+ # run_script takes a long time before failing on them, so+ # don't try to analyze them again+ failed_filenames.add(src_module.__file__)+ return False++ for found_module in itertools.chain([src_module], finder.modules.values()):+ if (+ hasattr(found_module, "__file__")+ and found_module.__file__ in target_filenames+ ):+ return True+ return False+++def _check_modules(+ modules: dict[str, types.ModuleType],+ reloader: ModuleReloader,+ failed_filenames: set[str],+) -> dict[str, types.ModuleType]:+ """Returns the set of modules used by the graph that have been modified"""+ stale_modules: dict[str, types.ModuleType] = {}+ modified_modules = reloader.check(modules=sys.modules, reload=False)+ for modname, module in modules.items():+ if _depends_on(+ src_module=module,+ target_filenames=set(+ m.__file__ for m in modified_modules if m.__file__ is not None+ ),+ failed_filenames=failed_filenames,+ ):+ stale_modules[modname] = module++ return stale_modules+++def watch_modules(+ graph: dataflow.DirectedGraph,+ mode: Literal["detect", "autorun"],+ enqueue_run_stale_cells: Callable[[], None],+ should_exit: threading.Event,+ run_is_processed: threading.Event,+ stream: Stream,+) -> None:+ """Watches for changes to modules used by graph++ The modules used by the graph are determined statically, by analyzing the+ modules imported by the notebook as well as the modules imported by those+ modules, recursively.+ """+ reloader = ModuleReloader()+ # modules that failed to be analyzed+ failed_filenames: set[str] = set()+ while not should_exit.is_set():+ run_is_processed.wait()+ time.sleep(1)+ # Collect the modules used by each cell+ modules: dict[str, types.ModuleType] = {}+ modname_to_cell_id: dict[str, CellId_t] = {}+ with graph.lock:+ for cell_id, cell in graph.cells.items():+ for modname in _modules_imported_by_cell(cell):+ if modname in sys.modules:+ modules[modname] = sys.modules[modname]+ modname_to_cell_id[modname] = cell_id+ stale_modules = _check_modules(+ modules=modules,+ reloader=reloader,+ failed_filenames=failed_filenames,+ )+ if stale_modules:+ with graph.lock:+ # If any modules are stale, communicate that to the FE+ stale_cell_ids = dataflow.transitive_closure(+ graph,+ set(+ modname_to_cell_id[modname]+ for modname in stale_modules+ ),+ )+ for cid in stale_cell_ids:+ graph.cells[cid].set_stale(stale=True, stream=stream)+ if mode == "autorun":+ run_is_processed.clear()+ enqueue_run_stale_cells()+++class ModuleWatcher:+ def __init__(+ self,+ graph: dataflow.DirectedGraph,+ mode: Literal["detect", "autorun"],+ enqueue_run_stale_cells: Callable[[], None],+ stream: Stream,+ ) -> None:+ # ModuleWatcher uses the graph to determine the modules used by the+ # notebook+ self.graph = graph+ # When set, signals the watcher thread to exit+ self.should_exit = threading.Event()+ # When False, an ExecuteStaleRequest is inflight to the kernel+ self.run_is_processed = threading.Event()+ self.run_is_processed.set()+ # To communicate staleness to the FE+ self.stream = stream+ # If autorun, stale cells are automatically scheduled for execution+ self.mode = mode+ # A callable that signals the kernel to run stale cells+ self.enqueue_run_stale_cells = enqueue_run_stale_cells+ threading.Thread(+ target=watch_modules,+ args=(+ self.graph,+ self.mode,+ self.enqueue_run_stale_cells,+ self.should_exit,+ self.run_is_processed,+ self.stream,+ ),+ daemon=True,+ ).start()++ def stop(self) -> None:+ self.should_exit.set()diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.pyindex 10d301f074..c46c9c4819 100644--- a/marimo/_runtime/requests.py+++ b/marimo/_runtime/requests.py@@ -20,6 +20,10 @@ class ExecutionRequest:code: str+@dataclass+class ExecuteStaleRequest: ...++@dataclassclass ExecuteMultipleRequest:execution_requests: List[ExecutionRequest]@@ -91,6 +95,7 @@ class InstallMissingPackagesRequest:ControlRequest = Union[ExecuteMultipleRequest,+ ExecuteStaleRequest,CreationRequest,DeleteRequest,FunctionCallRequest,diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex ac7fd014ab..d75cfa25a4 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -71,7 +71,6 @@ from marimo._runtime import (marimo_pdb,patches,)-from marimo._runtime.autoreload import ModuleReloaderfrom marimo._runtime.complete import complete, completion_workerfrom marimo._runtime.context import (ContextNotInitializedError,@@ -87,6 +86,8 @@ from marimo._runtime.packages.package_managers import create_package_managerfrom marimo._runtime.packages.utils import is_python_isolatedfrom marimo._runtime.query_params import QueryParamsfrom marimo._runtime.redirect_streams import redirect_streams+from marimo._runtime.reload.autoreload import ModuleReloader+from marimo._runtime.reload.module_watcher import ModuleWatcherfrom marimo._runtime.requests import (AppMetadata,CompletionRequest,@@ -94,6 +95,7 @@ from marimo._runtime.requests import (CreationRequest,DeleteRequest,ExecuteMultipleRequest,+ ExecuteStaleRequest,ExecutionRequest,FunctionCallRequest,InstallMissingPackagesRequest,@@ -246,6 +248,7 @@ class Kernel:- stdin: replacement for sys.stdin- input_override: a function that overrides the builtin input() function- debugger_override: a replacement for the built-in Pdb+ - execute_stale_cells_callback: callback to enqueue a stale cells request"""def __init__(@@ -257,6 +260,7 @@ class Kernel:stdout: Stdout | None,stderr: Stderr | None,stdin: Stdin | None,+ execute_stale_cells_callback: Callable[[], None],input_override: Callable[[Any], str] = input_override,debugger_override: marimo_pdb.MarimoPdb | None = None,) -> None:@@ -266,6 +270,7 @@ class Kernel:self.stdout = stdoutself.stderr = stderrself.stdin = stdin+ self.execute_stale_cells_callback = execute_stale_cells_callbackself.debugger = debugger_overrideif self.debugger is not None:@@ -294,11 +299,10 @@ class Kernel:self.module_registry = ModuleRegistry(self.graph, excluded_modules=set())-- # Load runtime settings from user configself.package_manager: PackageManager | None = Noneself.module_reloader: ModuleReloader | None = None- self.user_config = user_config+ self.module_watcher: ModuleWatcher | None = None+ # Load runtime settings from user configself._update_runtime_from_user_config(user_config)# Set up the execution context@@ -318,16 +322,38 @@ class Kernel:exec("import marimo as __marimo__", self.globals)def _update_runtime_from_user_config(self, config: MarimoConfig) -> None:- self.user_config = config- package_manager = self.user_config["package_management"]["manager"]- autoreload = self.user_config["runtime"]["auto_reload"]+ package_manager = config["package_management"]["manager"]+ autoreload_mode = config["runtime"]["auto_reload"]if (self.package_manager is Noneor package_manager != self.package_manager.name):self.package_manager = create_package_manager(package_manager)- if autoreload and self.module_reloader is None:- self.module_reloader = ModuleReloader()++ if autoreload_mode == "detect" or autoreload_mode == "autorun":+ if self.module_reloader is None:+ self.module_reloader = ModuleReloader()++ if (+ self.module_watcher is not None+ and self.module_watcher.mode != autoreload_mode+ ):+ self.module_watcher.stop()+ self.module_watcher = None++ if self.module_watcher is None:+ self.module_watcher = ModuleWatcher(+ self.graph,+ enqueue_run_stale_cells=self.execute_stale_cells_callback,+ mode=autoreload_mode,+ stream=self.stream,+ )+ else:+ self.module_reloader = None+ if self.module_watcher is not None:+ self.module_watcher.stop()++ self.user_config = config@propertydef globals(self) -> dict[Any, Any]:@@ -778,9 +804,11 @@ class Kernel:# cells that are disabled (explicitly or implicitly).for cid in cell_ids:if self.graph.is_disabled(cid):- self.graph.cells[cid].set_status(status="stale")+ self.graph.cells[cid].set_stale(stale=True)else:self.graph.cells[cid].set_status(status="queued")+ if self.graph.cells[cid].stale:+ self.graph.cells[cid].set_stale(stale=False)# State clean-up: don't leak names, UI elements, ...## Clean-up state for all cells upfront, before running@@ -1016,6 +1044,17 @@ class Kernel:self.mutate_graph(execution_requests, deletion_requests=[]))+ async def run_stale_cells(self) -> None:+ cells_to_run: set[CellId_t] = set()+ for cid, cell_impl in self.graph.cells.items():+ if cell_impl.stale and not self.graph.is_disabled(cid):+ cells_to_run.add(cid)+ await self._run_cells(+ dataflow.transitive_closure(self.graph, cells_to_run)+ )+ if self.module_watcher is not None:+ self.module_watcher.run_is_processed.set()+async def set_cell_config(self, request: SetCellConfigRequest) -> None:"""Update cell configs.@@ -1327,6 +1366,8 @@ class Kernel:elif isinstance(request, ExecuteMultipleRequest):await self.run(request.execution_requests)CompletedRun().broadcast()+ elif isinstance(request, ExecuteStaleRequest):+ await self.run_stale_cells()elif isinstance(request, SetCellConfigRequest):await self.set_cell_config(request)elif isinstance(request, SetUserConfigRequest):@@ -1408,6 +1449,9 @@ def launch_kernel(input_override=input_override,debugger_override=debugger,user_config=user_config,+ execute_stale_cells_callback=lambda: control_queue.put_nowait(+ ExecuteStaleRequest()+ ),)initialize_context(kernel=kernel,diff --git a/tests/_ast/test_compiler.py b/tests/_ast/test_compiler.pyindex ee883a17ff..03dcfaf6de 100644--- a/tests/_ast/test_compiler.py+++ b/tests/_ast/test_compiler.py@@ -25,7 +25,7 @@ class TestParseCell:cell = compile_cell(code)assert cell.defs == {"module", "y"}assert cell.refs == {"f", "x"}- assert cell.imported_modules == {"_secret_module"}+ assert cell.imported_namespaces == {"_secret_module"}@staticmethoddef test_dunder_dunder_excluded() -> None:@@ -49,7 +49,7 @@ class TestParseCell:assert cell.defs == {"m"}assert cell.refs == set()# but _m is the module from which it was imported- assert cell.imported_modules == {"_m"}+ assert cell.imported_namespaces == {"_m"}@staticmethoddef test_ref_local_var() -> None:@@ -62,7 +62,7 @@ class TestParseCell:cell = compile_cell(code)assert cell.defs == {"f"}assert cell.refs == set()- assert not cell.imported_modules+ assert not cell.imported_namespaces@staticmethoddef test_import() -> None:@@ -72,7 +72,7 @@ class TestParseCell:assert cell.defs == {"d", "x"}assert cell.refs == set()# but "a" is the module from which it was imported- assert cell.imported_modules == {"a"}+ assert cell.imported_namespaces == {"a"}class TestCellFactory:diff --git a/tests/_ast/test_visitor.py b/tests/_ast/test_visitor.pyindex 7432d21db0..ff76e24d08 100644--- a/tests/_ast/test_visitor.py+++ b/tests/_ast/test_visitor.py@@ -7,7 +7,7 @@ from inspect import cleandocimport pytestfrom marimo._ast import visitor-from marimo._ast.visitor import VariableData+from marimo._ast.visitor import ImportData, VariableDatadef test_assign_simple() -> None:@@ -629,7 +629,10 @@ def test_import_nested() -> None:v.visit(mod)assert v.defs == set(["a"])assert v.refs == set()- assert v.variable_data["a"] == VariableData(kind="import", module="a")+ assert v.variable_data["a"] == VariableData(+ kind="import",+ import_data=ImportData(module="a.b.c", imported_symbol=None),+ )def test_import_as() -> None:@@ -639,7 +642,10 @@ def test_import_as() -> None:v.visit(mod)assert v.defs == set(["d"])assert v.refs == set()- assert v.variable_data["d"] == VariableData(kind="import", module="a")+ assert v.variable_data["d"] == VariableData(+ kind="import",+ import_data=ImportData(module="a.b.c", imported_symbol=None),+ )def test_import_multiple() -> None:@@ -649,8 +655,13 @@ def test_import_multiple() -> None:v.visit(mod)assert v.defs == set(["a", "d"])assert v.refs == set()- assert v.variable_data["a"] == VariableData(kind="import", module="a")- assert v.variable_data["d"] == VariableData(kind="import", module="d")+ assert v.variable_data["a"] == VariableData(+ kind="import",+ import_data=ImportData(module="a.b.c", imported_symbol=None),+ )+ assert v.variable_data["d"] == VariableData(+ kind="import", import_data=ImportData(module="d", imported_symbol=None)+ )def test_from_import() -> None:@@ -661,7 +672,10 @@ def test_from_import() -> None:assert v.defs == set(["d"])assert v.refs == set()assert v.variable_data["d"] == VariableData(- kind="import", module="a", import_level=0+ kind="import",+ import_data=ImportData(+ module="a.b.c", imported_symbol="a.b.c.d", import_level=0+ ),)@@ -673,7 +687,10 @@ def test_relative_from_import() -> None:assert v.defs == set(["d"])assert v.refs == set()assert v.variable_data["d"] == VariableData(- kind="import", module="a", import_level=2+ kind="import",+ import_data=ImportData(+ module="a.b.c", imported_symbol="a.b.c.d", import_level=2+ ),)diff --git a/tests/_runtime/reload/conftest.py b/tests/_runtime/reload/conftest.pynew file mode 100644index 0000000000..972a3bf5ed--- /dev/null+++ b/tests/_runtime/reload/conftest.py@@ -0,0 +1,7 @@+import pytest+import reload_test_utils+++def py_modname() -> str:+ return reload_test_utils.random_modname()diff --git a/tests/_runtime/reload/reload_test_utils.py b/tests/_runtime/reload/reload_test_utils.pynew file mode 100644index 0000000000..5892739687--- /dev/null+++ b/tests/_runtime/reload/reload_test_utils.py@@ -0,0 +1,27 @@+import pathlib+import random+import textwrap+import time+++def random_modname():+ filename_chars = "abcdefghijklmopqrstuvwxyz"+ return "".join(random.sample(filename_chars, 20))+++def update_file(path: pathlib.Path, code: str) -> None:+ """+ Comment from+ https://github.com/ipython/ipython/blob/fe52b206ecd0e566fff935fea36d26e0903ec34b/IPython/extensions/tests/test_autoreload.py#L128++ Python's .pyc files record the timestamp of their compilation+ with a time resolution of one second.++ Therefore, we need to force a timestamp difference between .py+ and .pyc, without having the .py file be timestamped in the+ future, and without changing the timestamp of the .pyc file+ (because that is stored in the file). The only reliable way+ to achieve this seems to be to sleep.+ """+ time.sleep(1.05)+ path.write_text(textwrap.dedent(code))diff --git a/tests/_runtime/reload/test_autoreload.py b/tests/_runtime/reload/test_autoreload.pynew file mode 100644index 0000000000..805aab0075--- /dev/null+++ b/tests/_runtime/reload/test_autoreload.py@@ -0,0 +1,36 @@+from __future__ import annotations++import importlib+import pathlib+import sys+import textwrap++from reload_test_utils import update_file++from marimo._runtime.reload.autoreload import ModuleReloader+++def test_reload_function(tmp_path: pathlib.Path, py_modname: str):+ sys.path.append(str(tmp_path))+ reloader = ModuleReloader()+ py_file = tmp_path / pathlib.Path(py_modname + ".py")+ py_file.write_text(+ textwrap.dedent(+ """+ def foo():+ return 1+ """+ )+ )+ mod = importlib.import_module(py_modname)+ reloader.check(sys.modules, reload=False)+ assert mod.foo() == 1+ update_file(+ py_file,+ """+ def foo():+ return 2+ """,+ )+ reloader.check(sys.modules, reload=True)+ assert mod.foo() == 2diff --git a/tests/_runtime/reload/test_module_watcher.py b/tests/_runtime/reload/test_module_watcher.pynew file mode 100644index 0000000000..b27ae4e314--- /dev/null+++ b/tests/_runtime/reload/test_module_watcher.py@@ -0,0 +1,227 @@+import copy+import pathlib+import sys+import textwrap+import time+from queue import Queue++from reload_test_utils import random_modname, update_file++from marimo._config.config import DEFAULT_CONFIG+from marimo._runtime.requests import ExecuteStaleRequest, SetUserConfigRequest+from marimo._runtime.runtime import Kernel+from tests.conftest import ExecReqProvider+++# these tests use random filenames for modules because they share+# the same sys.modules object, and each test needs fresh modules+async def test_reload_function(+ tmp_path: pathlib.Path,+ py_modname: str,+ k: Kernel,+ exec_req: ExecReqProvider,+):+ sys.path.append(str(tmp_path))+ py_file = tmp_path / pathlib.Path(py_modname + ".py")+ py_file.write_text(+ textwrap.dedent(+ """+ def foo():+ return 1+ """+ )+ )++ config = copy.deepcopy(DEFAULT_CONFIG)+ config["runtime"]["auto_reload"] = "detect"+ k.set_user_config(SetUserConfigRequest(config=config))+ await k.run(+ [+ er_1 := exec_req.get(f"from {py_modname} import foo"),+ er_2 := exec_req.get("x = foo()"),+ er_3 := exec_req.get("pass"),+ ]+ )+ assert k.globals["x"] == 1+ update_file(+ py_file,+ """+ def foo():+ return 2+ """,+ )++ # wait for the watcher to pick up the change+ time.sleep(1.5)+ assert k.graph.cells[er_1.cell_id].stale+ assert k.graph.cells[er_2.cell_id].stale+ assert not k.graph.cells[er_3.cell_id].stale+ await k.run_stale_cells()+ assert not k.graph.cells[er_1.cell_id].stale+ assert not k.graph.cells[er_2.cell_id].stale+ assert not k.graph.cells[er_3.cell_id].stale+ assert k.globals["x"] == 2+++async def test_reload_nested_module_function(+ tmp_path: pathlib.Path,+ py_modname: str,+ k: Kernel,+ exec_req: ExecReqProvider,+):+ sys.path.append(str(tmp_path))+ b = tmp_path / (b_name := random_modname())+ b.mkdir()+ (b / "__init__.py").write_text("")++ c = b / (c_name := random_modname())+ c.mkdir()+ (c / "__init__.py").write_text("")++ nested_module = c / "mod.py"+ nested_module.write_text("func = lambda: 1")+ py_file = tmp_path / pathlib.Path(py_modname + ".py")+ py_file.write_text(+ textwrap.dedent(+ f"""+ from {b_name}.{c_name}.mod import func++ def foo():+ return func()+ """+ )+ )++ config = copy.deepcopy(DEFAULT_CONFIG)+ config["runtime"]["auto_reload"] = "detect"+ k.set_user_config(SetUserConfigRequest(config=config))+ await k.run(+ [+ er_1 := exec_req.get(f"from {py_modname} import foo"),+ er_2 := exec_req.get("x = foo()"),+ er_3 := exec_req.get("pass"),+ ]+ )+ assert k.globals["x"] == 1+ update_file(nested_module, "func = lambda : 2")++ # wait for the watcher to pick up the change+ time.sleep(1.5)+ assert k.graph.cells[er_1.cell_id].stale+ assert k.graph.cells[er_2.cell_id].stale+ assert not k.graph.cells[er_3.cell_id].stale+ await k.run_stale_cells()+ assert not k.graph.cells[er_1.cell_id].stale+ assert not k.graph.cells[er_2.cell_id].stale+ assert not k.graph.cells[er_3.cell_id].stale+ assert k.globals["x"] == 2+++async def test_reload_nested_module_import_module(+ tmp_path: pathlib.Path,+ py_modname: str,+ k: Kernel,+ exec_req: ExecReqProvider,+):+ sys.path.append(str(tmp_path))+ b = tmp_path / (b_name := random_modname())+ b.mkdir()+ (b / "__init__.py").write_text("")++ c = b / (c_name := random_modname())+ c.mkdir()+ (c / "__init__.py").write_text("")++ nested_module = c / "mod.py"+ nested_module.write_text("func = lambda: 1")+ py_file = tmp_path / pathlib.Path(py_modname + ".py")+ py_file.write_text(+ textwrap.dedent(+ f"""+ from {b_name}.{c_name} import mod++ def foo():+ return mod.func()+ """+ )+ )++ config = copy.deepcopy(DEFAULT_CONFIG)+ config["runtime"]["auto_reload"] = "detect"+ k.set_user_config(SetUserConfigRequest(config=config))+ await k.run(+ [+ er_1 := exec_req.get(f"from {py_modname} import foo"),+ er_2 := exec_req.get("x = foo()"),+ er_3 := exec_req.get("pass"),+ ]+ )+ assert k.globals["x"] == 1+ update_file(nested_module, "func = lambda : 2")++ # wait for the watcher to pick up the change+ time.sleep(1.5)+ assert k.graph.cells[er_1.cell_id].stale+ assert k.graph.cells[er_2.cell_id].stale+ assert not k.graph.cells[er_3.cell_id].stale+ await k.run_stale_cells()+ assert not k.graph.cells[er_1.cell_id].stale+ assert not k.graph.cells[er_2.cell_id].stale+ assert not k.graph.cells[er_3.cell_id].stale+ assert k.globals["x"] == 2+++async def test_reload_nested_module_import_module_autorun(+ tmp_path: pathlib.Path,+ py_modname: str,+ k: Kernel,+ exec_req: ExecReqProvider,+):+ sys.path.append(str(tmp_path))+ b = tmp_path / (b_name := random_modname())+ b.mkdir()+ (b / "__init__.py").write_text("")++ c = b / (c_name := random_modname())+ c.mkdir()+ (c / "__init__.py").write_text("")++ nested_module = c / "mod.py"+ nested_module.write_text("func = lambda: 1")+ py_file = tmp_path / pathlib.Path(py_modname + ".py")+ py_file.write_text(+ textwrap.dedent(+ f"""+ from {b_name}.{c_name} import mod++ def foo():+ return mod.func()+ """+ )+ )++ queue = Queue()+ k.execute_stale_cells_callback = lambda: queue.put(ExecuteStaleRequest())+ config = copy.deepcopy(DEFAULT_CONFIG)+ config["runtime"]["auto_reload"] = "autorun"+ k.set_user_config(SetUserConfigRequest(config=config))+ await k.run(+ [+ er_1 := exec_req.get(f"from {py_modname} import foo"),+ er_2 := exec_req.get("x = foo()"),+ er_3 := exec_req.get("pass"),+ ]+ )+ assert k.globals["x"] == 1+ update_file(nested_module, "func = lambda: 2")++ # wait for the watcher to pick up the change+ queue.get(timeout=2)+ assert k.graph.cells[er_1.cell_id].stale+ assert k.graph.cells[er_2.cell_id].stale+ assert not k.graph.cells[er_3.cell_id].stale+ await k.run_stale_cells()+ assert not k.graph.cells[er_1.cell_id].stale+ assert not k.graph.cells[er_2.cell_id].stale+ assert not k.graph.cells[er_3.cell_id].stale+ assert k.globals["x"] == 2diff --git a/tests/_runtime/test_autoreload.py b/tests/_runtime/test_autoreload.pydeleted file mode 100644index 2b92520648..0000000000--- a/tests/_runtime/test_autoreload.py+++ /dev/null@@ -1,96 +0,0 @@-from __future__ import annotations--import importlib-import pathlib-import random-import sys-import textwrap-import time--from marimo._config.config import DEFAULT_CONFIG, _deep_copy-from marimo._runtime.autoreload import ModuleReloader-from marimo._runtime.requests import SetUserConfigRequest-from marimo._runtime.runtime import Kernel-from tests.conftest import ExecReqProvider---def random_py_modname() -> str:- filename_chars = "abcdefghijklmopqrstuvwxyz"- return "".join(random.sample(filename_chars, 20))---def update_file(path: pathlib.Path, code: str) -> None:- """- Comment from- https://github.com/ipython/ipython/blob/fe52b206ecd0e566fff935fea36d26e0903ec34b/IPython/extensions/tests/test_autoreload.py#L128-- Python's .pyc files record the timestamp of their compilation- with a time resolution of one second.-- Therefore, we need to force a timestamp difference between .py- and .pyc, without having the .py file be timestamped in the- future, and without changing the timestamp of the .pyc file- (because that is stored in the file). The only reliable way- to achieve this seems to be to sleep.- """- time.sleep(1.05)- path.write_text(textwrap.dedent(code))---def test_reload_function(tmp_path: pathlib.Path):- sys.path.append(str(tmp_path))- reloader = ModuleReloader()- py_modname = random_py_modname()- py_file = tmp_path / pathlib.Path(py_modname + ".py")- py_file.write_text(- textwrap.dedent(- """- def foo():- return 1- """- )- )- mod = importlib.import_module(py_modname)- reloader.check(sys.modules, reload=False)- assert mod.foo() == 1- update_file(- py_file,- """- def foo():- return 2- """,- )- reloader.check(sys.modules, reload=True)- assert mod.foo() == 2---async def test_reload_function_kernel(- tmp_path: pathlib.Path, k: Kernel, exec_req: ExecReqProvider-):- sys.path.append(str(tmp_path))- py_modname = random_py_modname()- py_file = tmp_path / pathlib.Path(py_modname + ".py")- py_file.write_text(- textwrap.dedent(- """- def foo():- return 1- """- )- )-- config = _deep_copy(DEFAULT_CONFIG)- config["runtime"]["auto_reload"] = True- k.set_user_config(SetUserConfigRequest(config=config))- await k.run([exec_req.get(f"import {py_modname}; x={py_modname}.foo()")])- assert k.globals["x"] == 1- update_file(- py_file,- """- def foo():- return 2- """,- )-- await k.run([exec_req.get(f"y={py_modname}.foo()")])- assert k.globals["y"] == 2diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex 0d7ab43aa7..152593d0b2 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -881,6 +881,7 @@ def test_sys_path_updated(tmp_path: pathlib.Path):cell_configs={},user_config=DEFAULT_CONFIG,app_metadata=AppMetadata(query_params={}, filename=filename),+ execute_stale_cells_callback=lambda: None,)assert str(tmp_path) in sys.pathassert str(tmp_path) == sys.path[0]diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txtindex 86a478115b..433a27656b 100644--- a/tests/_server/templates/snapshots/export1.txt+++ b/tests/_server/templates/snapshots/export1.txt@@ -56,7 +56,7 @@<marimo-filename hidden>notebook.py</marimo-filename><marimo-mode data-mode='read' hidden></marimo-mode><marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": false}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default"}}' hidden></marimo-user-config>+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": "off"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default"}}' hidden></marimo-user-config><marimo-app-config data-config='{"layout_file": null, "width": "normal"}' hidden></marimo-app-config><marimo-server-token data-token='token' hidden></marimo-server-token><title>notebook</title>diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txtindex e4a3b3956e..2e999704df 100644--- a/tests/_server/templates/snapshots/export2.txt+++ b/tests/_server/templates/snapshots/export2.txt@@ -56,7 +56,7 @@<marimo-filename hidden></marimo-filename><marimo-mode data-mode='read' hidden></marimo-mode><marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": false}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default"}}' hidden></marimo-user-config>+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": "off"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default"}}' hidden></marimo-user-config><marimo-app-config data-config='{"layout_file": null, "width": "normal"}' hidden></marimo-app-config><marimo-server-token data-token='token' hidden></marimo-server-token><title>marimo</title>diff --git a/tests/_server/templates/snapshots/export3.txt b/tests/_server/templates/snapshots/export3.txtindex 7ef0244a7d..6abdb270b2 100644--- a/tests/_server/templates/snapshots/export3.txt+++ b/tests/_server/templates/snapshots/export3.txt@@ -56,7 +56,7 @@<marimo-filename hidden>notebook.py</marimo-filename><marimo-mode data-mode='read' hidden></marimo-mode><marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": false}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default"}}' hidden></marimo-user-config>+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": "off"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default"}}' hidden></marimo-user-config><marimo-app-config data-config='{"layout_file": null, "width": "normal"}' hidden></marimo-app-config><marimo-server-token data-token='token' hidden></marimo-server-token><title>notebook</title>diff --git a/tests/conftest.py b/tests/conftest.pyindex 366c7d37b9..a28be0653c 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -97,6 +97,7 @@ class MockedKernel:filename=None,),debugger_override=MarimoPdb(stdout=self.stdout, stdin=self.stdin),+ execute_stale_cells_callback=lambda: None,)initialize_context(