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
mep/8: frontend function hints (#4025)
Dylan Madisettic04aaefc4b5b
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex fa81c307f7..b6b3a476f1 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -1276,6 +1276,31 @@ export const UserConfigForm: React.FC = () => {</div>)}/>+ <FormField+ control={form.control}+ name="experimental.toplevel_defs"+ render={({ field }) => (+ <div className="flex flex-col gap-y-1">+ <FormItem className={formItemClasses}>+ <FormLabel className="font-normal">+ Library Save Format+ </FormLabel>+ <FormControl>+ <Checkbox+ data-testid="toplevel-defs-checkbox"+ checked={field.value === true}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </FormItem>+ <FormDescription>+ Enable saving in an experimental file format for marimo.+ This will expose functions that are defined in their own+ cell for function reuse and import by other programs.+ </FormDescription>{" "}+ </div>+ )}+ /></SettingGroup>);}diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex c83ac10381..d778baf17f 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -49,7 +49,11 @@ import { CollapsedCellBanner, CollapseToggle } from "./cell/collapse";import { canCollapseOutline } from "@/core/dom/outline";import { StopButton } from "@/components/editor/cell/StopButton";import type { CellConfig, RuntimeState } from "@/core/network/types";-import { HelpCircleIcon, MoreHorizontalIcon } from "lucide-react";+import {+ HelpCircleIcon,+ MoreHorizontalIcon,+ SquareFunctionIcon,+} from "lucide-react";import { Toolbar, ToolbarItem } from "@/components/editor/cell/toolbar";import { cn } from "@/utils/cn";import { isErrorMime } from "@/core/mime";@@ -340,6 +344,7 @@ export interface CellProps| "staleInputs"| "runStartTimestamp"| "lastRunStartTimestamp"+ | "serialization"| "runElapsedTimeMs"| "debuggerActive">,@@ -528,6 +533,7 @@ const EditableCellComponent = ({stopped,staleInputs,serializedEditorState,+ serialization,debuggerActive,appClosed,canDelete,@@ -832,10 +838,32 @@ const EditableCellComponent = ({</div></div>{cellOutput === "below" && outputArea}+ {serialization && (+ <div className="py-1 px-2 flex justify-end gap-2 last:rounded-b">+ <Tooltip+ content={<span className="max-w-16">{serialization}</span>}+ >+ {(serialization.toLowerCase() === "valid" && (+ <SquareFunctionIcon+ size={16}+ strokeWidth={1.5}+ className="rounded-lg text-muted-foreground"+ />+ )) || (+ <HelpCircleIcon+ size={16}+ strokeWidth={1.5}+ className="rounded-lg text-muted-foreground"+ />+ )}+ </Tooltip>+ </div>+ )}<ConsoleOutputconsoleOutputs={consoleOutputs}stale={consoleOutputStale}- cellName={name}+ // Empty name if serialization triggered+ cellName={serialization ? "_" : name}onRefactorWithAI={handleRefactorWithAI}onSubmitDebugger={(text, index) => {actions.setStdinResponse({diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsxindex 241ad57c8e..156f6caf21 100644--- a/frontend/src/components/editor/actions/useNotebookActions.tsx+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx@@ -378,7 +378,7 @@ export function useNotebookActions() {{icon: <DiamondPlusIcon size={14} strokeWidth={1.5} />,label: "Add setup cell",- hidden: !getFeatureFlag("setup_cell"),+ hidden: !getFeatureFlag("toplevel_defs"),handle: () => {upsertSetupCell({code: "# Initialization code that runs before all other cells",diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsxindex e72b41aef5..1e77e15237 100644--- a/frontend/src/components/editor/renderers/CellArray.tsx+++ b/frontend/src/components/editor/renderers/CellArray.tsx@@ -258,30 +258,17 @@ const CellColumn: React.FC<{theme={theme}showPlaceholder={hasOnlyOneCell}allowFocus={!invisible}- id={cellData.id}- code={cellData.code}- outline={cellRuntime.outline}- output={cellRuntime.output}- consoleOutputs={cellRuntime.consoleOutputs}- status={cellRuntime.status}- edited={cellData.edited}- interrupted={cellRuntime.interrupted}- errored={cellRuntime.errored}- stopped={cellRuntime.stopped}- staleInputs={cellRuntime.staleInputs}- runStartTimestamp={cellRuntime.runStartTimestamp}- lastRunStartTimestamp={cellRuntime.lastRunStartTimestamp}+ {...cellData}+ {...cellRuntime}runElapsedTimeMs={cellRuntime.runElapsedTimeMs ??(cellData.lastExecutionTime as Milliseconds)}- serializedEditorState={cellData.serializedEditorState}canDelete={!hasOnlyOneCell}mode={mode}appClosed={appClosed}ref={notebook.cellHandles[cellId]}userConfig={userConfig}- debuggerActive={cellRuntime.debuggerActive}config={cellData.config}name={cellData.name}isCollapsed={column.isCollapsed(cellId)}diff --git a/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap b/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snapindex 2e84b32c6e..000754c558 100644--- a/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap+++ b/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap@@ -80,6 +80,7 @@ exports[`cell reducer > can initialize stdin 3`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "queued",@@ -109,6 +110,7 @@ exports[`cell reducer > can initialize stdin 4`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "running",@@ -145,6 +147,7 @@ exports[`cell reducer > can initialize stdin 5`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "running",@@ -181,6 +184,7 @@ exports[`cell reducer > can initialize stdin 6`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "running",@@ -223,6 +227,7 @@ exports[`cell reducer > can initialize stdin 7`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "running",@@ -266,6 +271,7 @@ exports[`cell reducer > can initialize stdin 8`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "running",@@ -315,6 +321,7 @@ exports[`cell reducer > can initialize stdin 9`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "running",@@ -380,6 +387,7 @@ exports[`cell reducer > can receive console when the cell is idle and will clear"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "queued",@@ -416,6 +424,7 @@ exports[`cell reducer > can receive console when the cell is idle and will clear"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "queued",@@ -445,6 +454,7 @@ exports[`cell reducer > can receive console when the cell is idle and will clear"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "running",@@ -481,6 +491,7 @@ exports[`cell reducer > can receive console when the cell is idle and will clear"output": null,"runElapsedTimeMs": 2000,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "idle",@@ -510,6 +521,7 @@ exports[`cell reducer > can run a stale cell 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "queued",@@ -539,6 +551,7 @@ exports[`cell reducer > can run a stale cell 2`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": true,"status": "queued",@@ -568,6 +581,7 @@ exports[`cell reducer > can run a stopped cell 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "queued",@@ -597,6 +611,7 @@ exports[`cell reducer > can run a stopped cell 2`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "idle",@@ -637,6 +652,7 @@ exports[`cell reducer > can run a stopped cell 3`] = `},"runElapsedTimeMs": null,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "idle",@@ -677,6 +693,7 @@ exports[`cell reducer > can run a stopped cell 4`] = `},"runElapsedTimeMs": null,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "queued",@@ -706,6 +723,7 @@ exports[`cell reducer > can run a stopped cell 5`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 40,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "running",@@ -822,6 +840,7 @@ exports[`cell reducer > can run cell and receive cell messages 4`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "queued",@@ -851,6 +870,7 @@ exports[`cell reducer > can run cell and receive cell messages 5`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "running",@@ -887,6 +907,7 @@ exports[`cell reducer > can run cell and receive cell messages 6`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "running",@@ -928,6 +949,7 @@ exports[`cell reducer > can run cell and receive cell messages 7`] = `},"runElapsedTimeMs": 13000,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "idle",@@ -970,6 +992,7 @@ import numpy",},"runElapsedTimeMs": 13000,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "idle",@@ -1011,6 +1034,7 @@ exports[`cell reducer > can run cell and receive cell messages 9`] = `},"runElapsedTimeMs": 13000,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "idle",@@ -1053,6 +1077,7 @@ import numpy",},"runElapsedTimeMs": 13000,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "idle",@@ -1102,6 +1127,7 @@ import numpy",},"runElapsedTimeMs": 11000,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "idle",@@ -1149,6 +1175,7 @@ import numpy",},"runElapsedTimeMs": 11000,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "idle",@@ -1276,6 +1303,7 @@ exports[`cell reducer > errors reset status to idle 4`] = `},"runElapsedTimeMs": null,"runStartTimestamp": null,+ "serialization": undefined,"serializedEditorState": null,"staleInputs": false,"status": "idle",diff --git a/frontend/src/core/cells/cell.ts b/frontend/src/core/cells/cell.tsindex 90a2ccba39..880b31c6e5 100644--- a/frontend/src/core/cells/cell.ts+++ b/frontend/src/core/cells/cell.ts@@ -72,6 +72,7 @@ export function transitionCell(nextCell.output = message.output ?? nextCell.output;nextCell.staleInputs = message.stale_inputs ?? nextCell.staleInputs;nextCell.status = message.status ?? nextCell.status;+ nextCell.serialization = message.serialization;let didInterruptFromThisMessage = false;diff --git a/frontend/src/core/cells/types.ts b/frontend/src/core/cells/types.tsindex 4c006e61cf..c4aba79455 100644--- a/frontend/src/core/cells/types.ts+++ b/frontend/src/core/cells/types.ts@@ -105,6 +105,8 @@ export interface CellRuntimeState {lastRunStartTimestamp: Seconds | null;/** debugger active */debuggerActive: boolean;+ /** serialization message */+ serialization?: string | null;}export type WithResponse<T> = T & {diff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsxindex f8c4a7ce54..717a27ff42 100644--- a/frontend/src/core/config/feature-flag.tsx+++ b/frontend/src/core/config/feature-flag.tsx@@ -14,7 +14,7 @@ export interface ExperimentalFeatures {scratchpad: boolean;rtc_v2: boolean;reactive_tests: boolean;- setup_cell: boolean;+ toplevel_defs: boolean;// Add new feature flags here}@@ -26,7 +26,7 @@ const defaultValues: ExperimentalFeatures = {scratchpad: true,rtc_v2: false,reactive_tests: false,- setup_cell: false,+ toplevel_defs: false,};export function getFeatureFlag<T extends keyof ExperimentalFeatures>(diff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.pyindex 2ee858b5dd..9195741114 100644--- a/marimo/_ast/cell_manager.py+++ b/marimo/_ast/cell_manager.py@@ -24,7 +24,7 @@ from marimo._ast.compiler import (toplevel_cell_factory,)from marimo._ast.models import CellData-from marimo._ast.names import DEFAULT_CELL_NAME+from marimo._ast.names import DEFAULT_CELL_NAME, SETUP_CELL_NAMEfrom marimo._ast.pytest import process_for_pytestfrom marimo._types.ids import CellId_t@@ -146,7 +146,7 @@ class CellManager:) -> Cell:"""Registers cells when called through a context block."""cell = context_cell_factory(- cell_id=self.create_cell_id(),+ cell_id=CellId_t(SETUP_CELL_NAME),# NB. carry along the frame from the initial call.frame=frame,)diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.pyindex 4d79c8b960..10b6c511f2 100644--- a/marimo/_ast/codegen.py+++ b/marimo/_ast/codegen.py@@ -17,6 +17,7 @@ from marimo._ast.compiler import compile_cellfrom marimo._ast.names import DEFAULT_CELL_NAME, SETUP_CELL_NAMEfrom marimo._ast.toplevel import TopLevelExtraction, TopLevelStatusfrom marimo._ast.visitor import Name+from marimo._config.manager import get_default_config_managerfrom marimo._types.ids import CellId_tINDENT = " "@@ -236,7 +237,6 @@ def serialize(return generate_unparsable_cell(code=status.code, config=status.cell_config, name=status.name)-cell = status._cellassert cell is not Noneif not toplevel_fn:@@ -267,8 +267,6 @@ def generate_app_constructor(config: Optional[_AppConfig]) -> str:for key in default_config:if updates[key] == default_config[key]:updates.pop(key)- if config._toplevel_fn:- updates["_toplevel_fn"] = Truekwargs = tuple(f"{key}={_format_arg(value)}" for key, value in updates.items()@@ -306,11 +304,17 @@ def generate_filecontents(cell_configs: list[CellConfig],config: Optional[_AppConfig] = None,header_comments: Optional[str] = None,+ _toplevel_fn: bool = False,) -> str:"""Translates a sequences of codes (cells) to a Python file"""# Until an appropriate means of controlling top-level functions exists,# Let's keep it disabled by default.- toplevel_fn = config is not None and config._toplevel_fn+ toplevel_fn = (+ get_default_config_manager(current_path=None)+ .get_config()+ .get("experimental", {})+ .get("toplevel_defs", False)+ ) or _toplevel_fn# Update old internal cell names to the new onesfor idx, name in enumerate(names):diff --git a/marimo/_ast/toplevel.py b/marimo/_ast/toplevel.pyindex 7ee9bc1a74..041c94f7de 100644--- a/marimo/_ast/toplevel.py+++ b/marimo/_ast/toplevel.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport builtinsfrom enum import Enum-from typing import TYPE_CHECKING, Optional+from typing import TYPE_CHECKING, Literal, Optional, Union, get_argsfrom marimo._ast.app import InternalAppfrom marimo._ast.cell import CellConfig, CellImpl@@ -15,21 +15,28 @@ if TYPE_CHECKING:from collections.abc import Iterator# Constant for easy reuse in tests-HINT_UNPARSABLE = "Cannot parse cell."-HINT_BAD_NAME = (- "Top level definitions cannot be named 'app', '__name__' or "- "'__generated_with'"-)-HINT_NOT_SINGLE = "Cell must contain exactly one function definition"-HINT_ORDER_DEPENDENT = (- "Signature and decorators depend on {} defined out of correct cell order"-)-HINT_HAS_REFS = (- "Function contains references to variables {} which are not top level."-)-HINT_HAS_CLOSE_REFS = (- "Function contains references to variables {} which failed to be toplevel."-)+TopLevelInvalidHints = Literal[+ "Cannot parse cell.",+ (+ "Top level definitions cannot be named 'app', '__name__' or "+ "'__generated_with'"+ ),+ "Cell must contain exactly one function definition",+ "Signature and decorators depend on {} defined out of correct cell order",+ "Function contains references to variables {} which are not top level.",+ "Function contains references to variables {} which failed to be toplevel.",+]+(+ HINT_UNPARSABLE,+ HINT_BAD_NAME,+ HINT_NOT_SINGLE,+ HINT_ORDER_DEPENDENT,+ HINT_HAS_REFS,+ HINT_HAS_CLOSE_REFS,+) = get_args(TopLevelInvalidHints)++TopLevelHints = Union[Literal["Valid"], TopLevelInvalidHints]+HINT_VALID, *_ = get_args(TopLevelHints)class TopLevelType(Enum):@@ -56,7 +63,7 @@ class TopLevelStatus:self._type: TopLevelType = TopLevelType.UNPARSABLEself.dependencies: set[Name] = set()self._cell: Optional[CellImpl] = None- self.hint: Optional[str] = None+ self.hint: Optional[TopLevelHints] = Noneself.code = codeself.cell_config = cell_config@@ -125,7 +132,7 @@ class TopLevelStatus:self.demote(HINT_HAS_REFS.format(defined_refs))- def demote(self, hint: str) -> None:+ def demote(self, hint: TopLevelInvalidHints) -> None:self.type = TopLevelType.CELLself.hint = hint@@ -235,6 +242,9 @@ class TopLevelExtraction:# Don't change names of objects that are not toplevel.for status in self.cells.values():status.name = status._name+ # Set the hint of all valid cells to HINT_VALID+ for status in self.toplevel.values():+ status.hint = HINT_VALIDdef _resolve_dependencies(self) -> None:"""Resolve the dependencies of unresolved cells"""@@ -286,6 +296,19 @@ class TopLevelExtraction:_ = resolve(name)assert not self.unresolved+ @classmethod+ def from_cells(cls, cells: list[CellImpl]) -> TopLevelExtraction:+ codes = [cell.code for cell in cells]+ names = ["_" for cell in cells]+ cell_configs = [cell.config for cell in cells]++ from marimo._ast.codegen import get_setup_cell++ setup = get_setup_cell(codes, names, cell_configs, True)+ if setup:+ return cls(codes, names, cell_configs, setup.defs)+ return cls(codes, names, cell_configs, set())+@classmethoddef from_app(cls, app: InternalApp) -> TopLevelExtraction:codes = list(app.cell_manager.codes())diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex d332a788f0..f26486e8e6 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -25,6 +25,7 @@ from uuid import uuid4from marimo import _loggers as loggersfrom marimo._ast.app import _AppConfigfrom marimo._ast.cell import CellConfig, RuntimeStateType+from marimo._ast.toplevel import TopLevelHints, TopLevelStatusfrom marimo._data.models import (ColumnSummary,DataSourceConnection,@@ -110,12 +111,13 @@ class CellOp(Op):A CellOp's data has some optional fields:- 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, ...)- run_id - the run associated with this cell.+ 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, ...)+ run_id - the run associated with this cell.+ serialization - the serialization status of the cellOmitting a field means that its value should be unchanged!@@ -131,6 +133,7 @@ class CellOp(Op):status: Optional[RuntimeStateType] = Nonestale_inputs: Optional[bool] = Nonerun_id: Optional[RunId_t] = None+ serialization: Optional[str] = Nonetimestamp: float = field(default_factory=lambda: time.time())def __post_init__(self) -> None:@@ -312,6 +315,15 @@ class CellOp(Op):) -> None:CellOp(cell_id=cell_id, stale_inputs=stale).broadcast(stream)+ @staticmethod+ def broadcast_serialization(+ cell_id: CellId_t,+ serialization: TopLevelStatus,+ stream: Stream | None = None,+ ) -> None:+ status: Optional[TopLevelHints] = serialization.hint+ CellOp(cell_id=cell_id, serialization=status).broadcast(stream)+@dataclassclass HumanReadableStatus:diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.pyindex c1f592719e..5cd8bb7f78 100644--- a/marimo/_runtime/runner/hooks_post_execution.py+++ b/marimo/_runtime/runner/hooks_post_execution.py@@ -6,6 +6,7 @@ from typing import Callablefrom marimo import _loggersfrom marimo._ast.cell import CellImpl+from marimo._ast.toplevel import TopLevelExtractionfrom marimo._data.get_datasets import (get_datasets_from_variables,has_updates_to_datasource,@@ -340,6 +341,30 @@ def _broadcast_outputs()+@kernel_tracer.start_as_current_span("render_toplevel_defs")+def _render_toplevel_defs(+ cell: CellImpl,+ runner: cell_runner.Runner,+ run_result: cell_runner.RunResult,+) -> None:+ del run_result+ variable = cell.toplevel_variable+ if variable is not None:+ # TODO: Actually needs to run full extractor on graph extraction.++ ancestors = runner.graph.ancestors(cell.cell_id)+ # TODO: Technically, order does matter incase there is a type definition+ # or decorator.+ path = [cell] + [runner.graph.cells[cid] for cid in ancestors]+ extractor = TopLevelExtraction.from_cells(path)+ serialization = next(iter(extractor))++ CellOp.broadcast_serialization(+ serialization=serialization,+ cell_id=cell.cell_id,+ )++@kernel_tracer.start_as_current_span("run_pytest")def _attempt_pytest(cell: CellImpl,diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex ef26f2646f..d40997b81e 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -493,6 +493,14 @@ class Kernel:self._post_execution_hooks.append(_attempt_pytest)+ # Adds in a post_execution hook to run pytest immediately+ if user_config.get("experimental", {}).get("toplevel_defs", False):+ from marimo._runtime.runner.hooks_post_execution import (+ _render_toplevel_defs,+ )++ self._post_execution_hooks.append(_render_toplevel_defs)+self._globals_lock = threading.RLock()self._completion_worker_started = Falsediff --git a/marimo/_smoke_tests/app_fn.py b/marimo/_smoke_tests/app_fn.pyindex 7f8e776de6..f1abcf07cc 100644--- a/marimo/_smoke_tests/app_fn.py+++ b/marimo/_smoke_tests/app_fn.py@@ -1,11 +1,16 @@++import marimo-__generated_with = "0.11.2"-app = marimo.App(_toplevel_fn=True)+__generated_with = "0.11.19"+app = marimo.App()++with app.setup:+ import marimo as mo@app.cell(hide_code=True)-def _(mo):+def _():mo.md(r"""# @app.function smoke test@@ -20,6 +25,7 @@ def _(mo):@app.functiondef self_ref_fib(n: int) -> int:+ """This is my doc string"""if n == 0:return 0if n == 1:@@ -27,41 +33,46 @@ def self_ref_fib(n: int) -> int:return self_ref_fib(n - 1) + self_ref_fib(n - 2)[email protected](disabled=True, hide_code=True)[email protected](hide_code=True)def divide(x, y):return y / x@app.functiondef subtraction(a: "int", b: "int") -> "int":+ """This is new doc string"""return a - b@app.function# Comments inbetween-def multiply(a, b) -> "int":+def multiply(a, b) -> int:return a * b+def _():+ d = 13+ return++[email protected](hide_code=True)def addition(a: int, b: int) -> int:- # int is considered no good, re-eval+ # int is considered no good, re-eval.return a + b-def bad_divide_curry(divide):- # Has an external ref currently does not work- def bad_divide_curry(x):- # Filler line- # To push the error- return divide(0, x)- # With lines below- return (bad_divide_curry,)+# Has an external ref currently does not work+def bad_divide_curry(x):+ # Filler line+ # To push the error+ return divide(0, x)+ # With lines below@app.cell-def _(addition, multiply, self_ref_fib):+def _():# Should be be a regular cellprint(addition(21, 56))print(multiply(21, 56))@@ -69,16 +80,10 @@ def _(addition, multiply, self_ref_fib):return-def _(bad_divide_curry):- a = bad_divide_curry(1)- return (a,)--@app.celldef _():- import marimo as mo- return (mo,)+ a = bad_divide_curry(1)+ returnif __name__ == "__main__":diff --git a/openapi/api.yaml b/openapi/api.yamlindex bd3f018d06..97e383f3ae 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -184,6 +184,9 @@ components:run_id:nullable: truetype: string+ serialization:+ nullable: true+ type: stringstale_inputs:nullable: truetype: booleandiff --git a/openapi/src/api.ts b/openapi/src/api.tsindex 832038decc..f1ef4836c5 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -2300,6 +2300,7 @@ export interface components {name: "cell-op";output?: components["schemas"]["CellOutput"];run_id?: string | null;+ serialization?: string | null;stale_inputs?: boolean | null;status?: components["schemas"]["RuntimeState"];timestamp: number;diff --git a/tests/_ast/codegen_data/test_generate_filecontents_toplevel.py b/tests/_ast/codegen_data/test_generate_filecontents_toplevel.pyindex acbb70a979..effee8a077 100644--- a/tests/_ast/codegen_data/test_generate_filecontents_toplevel.py+++ b/tests/_ast/codegen_data/test_generate_filecontents_toplevel.py@@ -7,7 +7,7 @@import marimo__generated_with = "0.0.0"-app = marimo.App(_toplevel_fn=True)+app = marimo.App()with app.setup:import iodiff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.pyindex be5290eb53..4f7786c102 100644--- a/tests/_ast/test_codegen.py+++ b/tests/_ast/test_codegen.py@@ -82,6 +82,7 @@ def get_idempotent_marimo_source(name: str) -> str:list(app._cell_manager.configs()),app._config,header_comments,+ _toplevel_fn=True,)generated_contents = sanitized_version(generated_contents)diff --git a/tests/_ast/test_pytest_toplevel.py b/tests/_ast/test_pytest_toplevel.pyindex f3570d96c4..7e0a61354d 100644--- a/tests/_ast/test_pytest_toplevel.py+++ b/tests/_ast/test_pytest_toplevel.py@@ -3,7 +3,7 @@import marimo__generated_with = "0.0.0"-app = marimo.App(_toplevel_fn=True)+app = marimo.App()with app.setup:# Special setup cell