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: top-level await (#795)
Akshay Agrawala5a839930f88
diff --git a/frontend/public/files/wasm-intro.py b/frontend/public/files/wasm-intro.pyindex 8f7ca2c608..6ad7801fa2 100644--- a/frontend/public/files/wasm-intro.py+++ b/frontend/public/files/wasm-intro.py@@ -2,7 +2,7 @@import marimo-__generated_with = "0.2.4"+__generated_with = "0.2.6"app = marimo.App()@@ -10,45 +10,60 @@ app = marimo.App()def __():import marimo as mo- mo.md("# Welcome to marimo running in WASM! 🌊🍃")+ mo.md("# Welcome to [marimo](https://github.com/marimo-team/marimo)! 🌊🍃")return mo,[email protected](hide_code=True)def __(mo):- slider = mo.ui.slider(1, 22)- return slider,---def __(mo, slider):mo.md(- f"""- marimo is a **reactive** Python notebook.-- This means that unlike traditional notebooks, marimo notebooks **run- automatically** when you modify them or- interact with UI elements, like this slider: {slider}.+ """+ **This marimo notebook is powered by [WASM](https://webassembly.org/)**:+ it's running entirely in your browser!- {"##" + "🍃" * slider.value}"""+ ).callout()+ return++[email protected](hide_code=True)+def __(mo):+ mo.accordion(+ {+ "When should I use WASM notebooks?": """+ WASM notebooks are excellent for sharing:+ because they run entirely in the browser, they are extremely+ easy to share. Just open the notebook action menu at the top-right and+ click the "Share WASM notebook" button to get a shareable URL. You can+ also embed your notebook in other webpages via an `<iframe>`.++ WASM are well-suited for quickly experimenting with code and+ models, doing lightweight data analysis, authoring blog+ posts, tutorials, and educational articles, and even building internal+ tools. They are not well-suited for notebooks that do heavy+ computation, and they don't support multi-threading nor+ multiprocessing; for these cases, use a regular marimo notebook.+ """+ })return[email protected](hide_code=True)def __(mo):mo.accordion({- "Installing packages": mo.md(+ "Installing packages in WASM notebooks": mo.md("""- Most packages will be automatically installed,+ Many packages will be automatically installed,These can be found at [packages-in-pyodide](https://pyodide.org/en/stable/usage/packages-in-pyodide.html).-- For those that are not, you can use this `install` function++ For other packages, use micropip:```python- install("altair")+ import micropip+ await micropip.install("plotly")+ import plotly```""")@@ -57,16 +72,26 @@ def __(mo):return[email protected](hide_code=True)-def __():- import micropip- import asyncio+def __(mo):+ slider = mo.ui.slider(1, 22)+ return slider,+++def __(mo, slider):+ mo.md(+ f"""+ marimo is a **reactive** Python notebook.+ This means that unlike traditional notebooks, marimo notebooks **run+ automatically** when you modify them or+ interact with UI elements, like this slider: {slider}.- def install(pkg):- loop = asyncio.get_event_loop()- loop.run_until_complete(micropip.install(pkg))- return asyncio, install, micropip+ {"##" + "🍃" * slider.value}+ """+ )+ return@app.cell(hide_code=True)diff --git a/frontend/src/core/pyodide/worker/bootstrap.ts b/frontend/src/core/pyodide/worker/bootstrap.tsindex 9aef37f84b..20987c1c7a 100644--- a/frontend/src/core/pyodide/worker/bootstrap.ts+++ b/frontend/src/core/pyodide/worker/bootstrap.ts@@ -24,7 +24,7 @@ export async function bootstrap() {const marimoWheel =process.env.NODE_ENV === "production"? "marimo >= 0.2.5"- : "http://localhost:8000/dist/marimo-0.2.5-py3-none-any.whl";+ : "http://localhost:8000/dist/marimo-0.2.6-py3-none-any.whl";await pyodide.runPythonAsync(`import micropipdiff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex 4b965daf9e..c88571f2bb 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import asyncioimport randomimport stringfrom collections.abc import Sequence@@ -22,7 +23,7 @@ from marimo._ast.cell import (CellFuncType,CellFuncTypeBound,CellId_t,- execute_cell,+ execute_cell_async,)from marimo._ast.compiler import cell_factoryfrom marimo._ast.errors import (@@ -194,7 +195,8 @@ class App:finally:self._initialized = True- def run(self) -> tuple[Sequence[Any], dict[str, Any]]:+ async def _run_async(self) -> tuple[Sequence[Any], dict[str, Any]]:+ # TODO: We'll maybe expose this in the futureif self._unparsable:raise UnparsableError("This app can't be run because it has unparsable cells."@@ -206,7 +208,6 @@ class App:# function is only called when running as a scriptwith patch_main_module_context() as module:glbls = module.__dict__-# Execute cells and collect outputsoutputs: dict[CellId_t, Any] = {}for cid in self._execution_order:@@ -214,7 +215,9 @@ class App:cid).cell_functionif cell_function is not None:- outputs[cid] = execute_cell(cell_function.cell, glbls)+ outputs[cid] = await execute_cell_async(+ cell_function.cell, glbls+ )# Return# - the outputs, sorted in the order that cells were added to the@@ -232,6 +235,9 @@ class App:{name: glbls[name] for name in self._defs if name in glbls},)+ def run(self) -> tuple[Sequence[Any], dict[str, Any]]:+ return asyncio.run(self._run_async())+class CellManager:"""diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex d842648b8c..67461f1d2e 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -71,6 +71,12 @@ class CellStatus:state: Optional[CellStatusType] = None+def _is_coroutine(code: Optional[CodeType]) -> bool:+ if code is None:+ return False+ return inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE++@dataclasses.dataclass(frozen=True)class Cell:# hash of code@@ -122,6 +128,9 @@ class Cell:if data.module is not None)+ def is_coroutine(self) -> bool:+ return _is_coroutine(self.body) or _is_coroutine(self.last_expr)+def set_status(self, status: CellStatusType) -> None:from marimo._messaging.ops import CellOpfrom marimo._runtime.context import (@@ -177,12 +186,7 @@ def cell_function(parameters = list(signature.parameters.keys())return_names = sorted(defn for defn in cell.defs)- @functools.wraps(f)- def func(*args: Any, **kwargs: Any) -> tuple[Any, ...]:- """Wrapper for executing cell using the function's signature.-- Alternative for passing a globals dict- """+ def _prepare_args(*args: Any, **kwargs: Any) -> dict[Any, Any]:glbls = {}glbls.update(defaults)pos = 0@@ -204,18 +208,39 @@ def cell_function()else:glbls[kwarg] = value+ return glbls- # we use execute_cell instead of calling `f` directly because- # we want to obtain the cell's HTML output, which is the last- # expression in the cell body.- #- # TODO: stash output if mo.collect_outputs() context manager is active- # ... or just make cell execution return the output in addition- # to the defs, which might be weird because that doesn't- # match the function signature- _ = execute_cell(cell, glbls)+ def _returns(glbls: dict[Any, Any]) -> tuple[Any, ...]:return tuple(glbls[name] for name in return_names)+ # Wrapper for executing cell using the function's signature.+ #+ # Alternative for passing a globals dict+ #+ # we use execute_cell instead of calling `f` directly because+ # we want to obtain the cell's HTML output, which is the last+ # expression in the cell body.+ #+ # TODO: stash output if mo.collect_outputs() context manager is active+ # ... or just make cell execution return the output in addition+ # to the defs, which might be weird because that doesn't+ # match the function signature+ if inspect.iscoroutinefunction(f):++ @functools.wraps(f)+ async def func(*args: Any, **kwargs: Any) -> tuple[Any, ...]:+ glbls = _prepare_args(*args, **kwargs)+ _ = await execute_cell_async(cell, glbls)+ return _returns(glbls)++ else:++ @functools.wraps(f)+ def func(*args: Any, **kwargs: Any) -> tuple[Any, ...]:+ glbls = _prepare_args(*args, **kwargs)+ _ = execute_cell(cell, glbls)+ return _returns(glbls)+cell_func = cast(CellFunction[CellFuncTypeBound], func)cell_func.cell = cellcell_func.args = args@@ -227,6 +252,22 @@ def is_ws(char: str) -> bool:return char == " " or char == "\n" or char == "\t"+async def execute_cell_async(cell: Cell, glbls: dict[Any, Any]) -> Any:+ if cell.body is None:+ return None+ assert cell.last_expr is not None++ if _is_coroutine(cell.body):+ await eval(cell.body, glbls)+ else:+ exec(cell.body, glbls)++ if _is_coroutine(cell.last_expr):+ return await eval(cell.last_expr, glbls)+ else:+ return eval(cell.last_expr, glbls)++def execute_cell(cell: Cell, glbls: dict[Any, Any]) -> Any:if cell.body is None:return Nonediff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.pyindex ab05687794..9d4e1d746c 100644--- a/marimo/_ast/codegen.py+++ b/marimo/_ast/codegen.py@@ -69,6 +69,9 @@ def to_functiondef(decorator = _to_decorator(cell.config)signature = f"def {name}({args}):"+ if cell.is_coroutine():+ signature = "async " + signature+if len(INDENT + signature) >= MAX_LINE_LENGTH:signature = f"def {name}{_multiline_tuple(refs)}:"fndef = decorator + "\n" + signature + "\n"diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.pyindex 9943dfc063..3178269eba 100644--- a/marimo/_ast/compiler.py+++ b/marimo/_ast/compiler.py@@ -52,7 +52,12 @@ def cache(filename: str, code: str) -> None:def compile_cell(code: str, cell_id: CellId_t) -> Cell:- module = ast.parse(code, mode="exec")+ module = compile(+ code,+ "<unknown>",+ mode="exec",+ flags=ast.PyCF_ONLY_AST | ast.PyCF_ALLOW_TOP_LEVEL_AWAIT,+ )if not module.body:# either empty code or just commentsreturn Cell(@@ -73,7 +78,7 @@ def compile_cell(code: str, cell_id: CellId_t) -> Cell:expr: Union[ast.Expression, str]if isinstance(module.body[-1], ast.Expr):- expr = ast.Expression(module.body.pop().value) # type: ignore+ expr = ast.Expression(module.body.pop().value)else:expr = "None"@@ -88,8 +93,9 @@ def compile_cell(code: str, cell_id: CellId_t) -> Cell:last_expr_filename,ast.unparse(expr) if not isinstance(expr, str) else "None",)- body = compile(module, body_filename, mode="exec")- last_expr = compile(expr, last_expr_filename, mode="eval")+ flags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT+ body = compile(module, body_filename, mode="exec", flags=flags)+ last_expr = compile(expr, last_expr_filename, mode="eval", flags=flags)glbls = {name for name in v.defs if not is_local(name)}return Cell(diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.pyindex 4cc011c72c..c779c4465a 100644--- a/marimo/_pyodide/pyodide_session.py+++ b/marimo/_pyodide/pyodide_session.py@@ -337,7 +337,7 @@ def launch_pyodide_kernel(while True:request = await control_queue.get()LOGGER.debug("received request %s", request)- kernel.handle_message(request)+ await kernel.handle_message(request)return RestartableTask(listen)diff --git a/marimo/_runtime/cell_runner.py b/marimo/_runtime/cell_runner.pyindex fc11d85666..6d37ccbe7c 100644--- a/marimo/_runtime/cell_runner.py+++ b/marimo/_runtime/cell_runner.py@@ -1,13 +1,17 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import asyncio+import contextlib+import functools+import signalimport sysimport tracebackfrom collections.abc import Containerfrom dataclasses import dataclass-from typing import TYPE_CHECKING, Any, Optional+from typing import TYPE_CHECKING, Any, Iterator, Optional-from marimo._ast.cell import CellId_t, execute_cell+from marimo._ast.cell import CellId_t, execute_cell, execute_cell_asyncfrom marimo._ast.compiler import cell_id_from_filenamefrom marimo._loggers import marimo_loggerfrom marimo._runtime import dataflow@@ -114,6 +118,53 @@ class Runner:cell_id: index for index, cell_id in enumerate(self.cells_to_run)}+ # Adapted from+ # https://github.com/ipython/ipykernel/blob/eddd3e666a82ebec287168b0da7cfa03639a3772/ipykernel/ipkernel.py#L312 # noqa: E501+ @staticmethod+ @contextlib.contextmanager+ def _cancel_on_sigint(future: asyncio.Future[Any]) -> Iterator[None]:+ """ContextManager for capturing SIGINT and cancelling a future++ SIGINT raises in the event loop when running async code,+ but we want it to halt a coroutine.++ Ideally, it would raise KeyboardInterrupt, but this turns it into a+ CancelledError.+ """+ sigint_future: asyncio.Future[int] = asyncio.Future()++ # whichever future finishes first,+ # cancel the other one+ def cancel_unless_done(f: asyncio.Future[Any], _: Any) -> None:+ if f.cancelled() or f.done():+ return+ f.cancel()++ # when sigint finishes,+ # abort the coroutine with CancelledError+ sigint_future.add_done_callback(+ functools.partial(cancel_unless_done, future)+ )+ # when the main future finishes,+ # stop watching for SIGINT events+ future.add_done_callback(+ functools.partial(cancel_unless_done, sigint_future)+ )++ def handle_sigint(*_: Any) -> None:+ if sigint_future.cancelled() or sigint_future.done():+ return+ # mark as done, to trigger cancellation+ sigint_future.set_result(1)++ # set the custom sigint handler during this context+ save_sigint = signal.signal(signal.SIGINT, handle_sigint)+ try:+ yield+ finally:+ # restore the previous sigint handler+ signal.signal(signal.SIGINT, save_sigint)+def cancel(self, cell_id: CellId_t) -> None:"""Mark a cell (and its descendants) as cancelled."""self.cells_cancelled[cell_id] = set(@@ -220,15 +271,25 @@ class Runner:error_msg = format_traceback(self.graph)sys.stderr.write(error_msg)- def run(self, cell_id: CellId_t) -> RunResult:+ async def run(self, cell_id: CellId_t) -> RunResult:"""Run a cell."""cell = self.graph.cells[cell_id]try:- return_value = execute_cell(cell, self.glbls)+ if cell.is_coroutine():+ return_value_future = asyncio.ensure_future(+ execute_cell_async(cell, self.glbls)+ )+ with Runner._cancel_on_sigint(return_value_future):+ return_value = await return_value_future+ else:+ return_value = execute_cell(cell, self.glbls)run_result = RunResult(output=return_value, exception=None)- except MarimoInterrupt as e:+ except (MarimoInterrupt, asyncio.exceptions.CancelledError) as e:# User interrupt# interrupt the entire runner+ if isinstance(e, asyncio.exceptions.CancelledError):+ # Async cells can only be cancelled via a user interrupt+ e = MarimoInterrupt()self.interrupted = Truerun_result = RunResult(output=None, exception=e)self.print_traceback()diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex d7921b32f6..14e2e1cdf4 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import asyncioimport builtinsimport contextlibimport dataclasses@@ -175,6 +176,11 @@ class Kernel:Args:- cell_configs: initial configuration for each cell+ - app_metadata: metadata about the notebook+ - stream: object used to communicate with the server/outside world+ - stdout: replacement for sys.stdout+ - stderr: replacement for sys.stderr+ - stdin: replacement for sys.stdin- input_override: a function that overrides the builtin input() function"""@@ -600,7 +606,7 @@ class Kernel:).broadcast()return descendants- def _run_cells(self, cell_ids: set[CellId_t]) -> None:+ async def _run_cells(self, cell_ids: set[CellId_t]) -> None:"""Run cells and any state updates they trigger"""# This patch is an attempt to mitigate problems caused by the fact@@ -609,14 +615,18 @@ class Kernel:# common cases. We could also be more aggressive and run this before# every cell, or even before pickle.dump/pickle.dumps()patches.patch_sys_module(self._module)- while cells_with_stale_state := self._run_cells_internal(cell_ids):+ while cells_with_stale_state := await self._run_cells_internal(+ cell_ids+ ):LOGGER.debug("Running state updates ...")cell_ids = dataflow.transitive_closure(self.graph, cells_with_stale_state)LOGGER.debug("Finished run.")- def _run_cells_internal(self, cell_ids: set[CellId_t]) -> set[CellId_t]:+ async def _run_cells_internal(+ self, cell_ids: set[CellId_t]+ ) -> set[CellId_t]:"""Run cells, send outputs to frontendsReturns set of cells that need to be re-run due to state updates.@@ -667,7 +677,7 @@ class Kernel:cell.set_status(status="running")with self._install_execution_context(cell_id) as exc_ctx:- run_result = runner.run(cell_id)+ run_result = await runner.run(cell_id)# Don't rebroadcast an output that was already sent## 1. if run_result.output is not None, need to send it@@ -821,29 +831,34 @@ class Kernel:# TODO(akshayka): Send VariableValues message for any globals# bound to this state object (just like UI elements)- def delete(self, request: DeleteRequest) -> None:+ async def delete(self, request: DeleteRequest) -> None:"""Delete a cell from kernel and graph."""cell_id = request.cell_idif cell_id in self.graph.cells:- self._run_cells(+ await self._run_cells(self.mutate_graph(execution_requests=[], deletion_requests=[request]))- def run(self, execution_requests: Sequence[ExecutionRequest]) -> None:+ async def run(+ self, execution_requests: Sequence[ExecutionRequest]+ ) -> None:"""Run cells and their descendants.+The cells may be cells already existing in the graph or new cells.Adds the cells in `execution_requests` to the graph before runningthem.++ Cells may use top-level await, which is why this function is async."""- self._run_cells(+ await self._run_cells(self.mutate_graph(execution_requests, deletion_requests=[]))- def set_cell_config(self, request: SetCellConfigRequest) -> None:+ async def set_cell_config(self, request: SetCellConfigRequest) -> None:"""Update cell configs.Cells that are enabled (via config) but stale are run as a side-effect.@@ -867,11 +882,13 @@ class Kernel:self.graph.disable_cell(cell_id)if cells_to_run:- self._run_cells(+ await self._run_cells(dataflow.transitive_closure(self.graph, cells_to_run))- def set_ui_element_value(self, request: SetUIElementValueRequest) -> None:+ async def set_ui_element_value(+ self, request: SetUIElementValueRequest+ ) -> None:"""Set the value of a UI element bound to a global variable.Runs cells that reference the UI element by name.@@ -983,7 +1000,7 @@ class Kernel:if variable_values:VariableValues(variables=variable_values).broadcast()- self._run_cells(+ await self._run_cells(dataflow.transitive_closure(self.graph, referring_cells))@@ -1060,7 +1077,7 @@ class Kernel:None,)- def instantiate(self, request: CreationRequest) -> None:+ async def instantiate(self, request: CreationRequest) -> None:"""Instantiate the kernel with cells and UIElement initial valuesDuring instantiation, UIElements can check for an initial value@@ -1076,23 +1093,23 @@ class Kernel:initial_value,) in request.set_ui_element_value_request.ids_and_values:self.ui_initializers[object_id] = initial_value- self.run(request.execution_requests)+ await self.run(request.execution_requests)self.reset_ui_initializers()- def handle_message(self, request: ControlRequest) -> None:+ async def handle_message(self, request: ControlRequest) -> None:"""Handle a message from the client.The message is dispatched to the appropriate method based on its type."""if isinstance(request, CreationRequest):- self.instantiate(request)+ await self.instantiate(request)CompletedRun().broadcast()elif isinstance(request, ExecuteMultipleRequest):- self.run(request.execution_requests)+ await self.run(request.execution_requests)CompletedRun().broadcast()elif isinstance(request, SetCellConfigRequest):- self.set_cell_config(request)+ await self.set_cell_config(request)elif isinstance(request, SetUIElementValueRequest):- self.set_ui_element_value(request)+ await self.set_ui_element_value(request)CompletedRun().broadcast()elif isinstance(request, FunctionCallRequest):status, ret = self.function_call_request(request)@@ -1103,7 +1120,7 @@ class Kernel:).broadcast()CompletedRun().broadcast()elif isinstance(request, DeleteRequest):- self.delete(request)+ await self.delete(request)elif isinstance(request, StopRequest):return Noneelse:@@ -1236,17 +1253,24 @@ def launch_kernel(else:signal.signal(signal.SIGTERM, sigterm_handler)- while True:- try:- request = control_queue.get()- except Exception as e:- # triggered on Windows when quit with Ctrl+C- LOGGER.debug("kernel queue.get() failed %s", e)- break- LOGGER.debug("received request %s", request)- if isinstance(request, StopRequest):- break- kernel.handle_message(request)+ async def control_loop() -> None:+ while True:+ try:+ request = control_queue.get()+ except Exception as e:+ # triggered on Windows when quit with Ctrl+C+ LOGGER.debug("kernel queue.get() failed %s", e)+ break+ LOGGER.debug("received request %s", request)+ if isinstance(request, StopRequest):+ break+ await kernel.handle_message(request)++ # The control loop is asynchronous only because we allow user code to use+ # top-level await; nothing else is awaited. Don't introduce async+ # primitives anywhere else in the runtime unless there is a *very* good+ # reason; prefer using threads (for performance and clarity).+ asyncio.run(control_loop())if stdout is not None:stdout._watcher.stop()diff --git a/pyproject.toml b/pyproject.tomlindex 1a0b35742b..95dc930c3a 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -199,6 +199,7 @@ addopts = "-ra -q -v --ignore tests/_cli/ipynb_data --ignore tests/_ast/codegen_testpaths = ["tests",]+asyncio_mode = "auto"[tool.coverage.run]omit = ["marimo/_tutorials/*"]diff --git a/tests/_ast/codegen_data/test_generate_filecontents_async.py b/tests/_ast/codegen_data/test_generate_filecontents_async.pynew file mode 100644index 0000000000..20d6633c18--- /dev/null+++ b/tests/_ast/codegen_data/test_generate_filecontents_async.py@@ -0,0 +1,30 @@+import marimo++__generated_with = "0.1.0"+app = marimo.App()+++def one():+ import numpy as np+ import asyncio+ return asyncio, np+++async def two(asyncio):+ x = 0+ xx = 1+ await asyncio.sleep(1)+ return x, xx+++def three(asyncio, x):+ async def _():+ await asyncio.sleep(x)+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.pyindex 5c1aa1a08a..4972ea1268 100644--- a/tests/_ast/test_app.py+++ b/tests/_ast/test_app.py@@ -355,3 +355,28 @@ class TestApp:_, defs = app.run()assert defs["out"] is not None++ @staticmethod+ def test_run_async() -> None:+ app = App()++ @app.cell+ async def __() -> tuple[Any, int]:+ import asyncio++ await asyncio.sleep(0.01)+ x = 0+ return (+ asyncio,+ x,+ )++ @app.cell+ def __(x: int) -> tuple[int]:+ y = x + 1+ return (y,)++ _, defs = app.run()++ assert defs["x"] == 0+ assert defs["y"] == 1diff --git a/tests/_ast/test_app_cell.py b/tests/_ast/test_app_cell.pyindex fbd7ae00c0..9f71e4c0b3 100644--- a/tests/_ast/test_app_cell.py+++ b/tests/_ast/test_app_cell.py@@ -1,6 +1,8 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import inspect+from marimo._ast.app import Appfrom marimo._ast.cell import CellFunction, CellFuncType@@ -75,3 +77,22 @@ def test_decorator_with_unknown_args() -> None:assert cell_function.__name__ == "__"assert cell_function.__call__ is not Noneassert cell_function.__call__() == (4,)+++async def test_decorator_async() -> None:+ # Decorator uncalled+ @app.cell+ async def __(asyncio) -> tuple[int]:+ await asyncio.sleep(0.1)+ z = 3 + 3+ return (z,)++ assert inspect.iscoroutinefunction(cell_function)+ assert cell_function.cell.config.disabled is False+ assert len(cell_function.args) == 1+ assert cell_function.__name__ == "__"+ assert cell_function.__call__ is not None++ import asyncio++ assert (await cell_function(asyncio)) == (6,)diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.pyindex 57e1b62ce1..63c112199c 100644--- a/tests/_ast/test_codegen.py+++ b/tests/_ast/test_codegen.py@@ -67,6 +67,18 @@ class TestGeneration:"test_generate_filecontents")+ @staticmethod+ def test_generate_filecontents_async() -> None:+ cell_one = "import numpy as np\nimport asyncio"+ cell_two = "x = 0\nxx = 1\nawait asyncio.sleep(1)"+ cell_three = "async def _():\n await asyncio.sleep(x)"+ codes = [cell_one, cell_two, cell_three]+ names = ["one", "two", "three"]+ contents = generate_filecontents(codes, names)+ assert contents == get_expected_filecontents(+ "test_generate_filecontents_async"+ )+@staticmethoddef test_generate_filecontents_single_cell() -> None:cell_one = "import numpy as np"@@ -104,6 +116,20 @@ class TestGeneration:# leading 4 spaces followed by nothingassert stringified[3] == " " * 4+ @staticmethod+ def test_generate_unparsable_cell_with_await() -> None:+ code = " await error\n\\t"+ raw = codegen.generate_unparsable_cell(code, None, CellConfig())+ stringified = eval("\n".join(raw.split("\n")[1:5])).split("\n")+ # first line empty+ assert not stringified[0]+ # leading 4 spaces followed by source line+ assert stringified[1] == " " * 4 + " await error"+ # leading 4 spaces followed by source line+ assert stringified[2] == " " * 4 + "\\t"+ # leading 4 spaces followed by nothing+ assert stringified[3] == " " * 4+@staticmethoddef test_long_line_in_main() -> None:cell_one = "\n".join(@@ -164,6 +190,22 @@ class TestGetCodes:"# just a comment",]+ @staticmethod+ def test_get_codes_async() -> None:+ app = codegen.get_app(get_filepath("test_generate_filecontents_async"))+ assert app is not None+ cell_manager = app._cell_manager+ assert list(cell_manager.names()) == [+ "one",+ "two",+ "three",+ ]+ assert list(cell_manager.codes()) == [+ "import numpy as np\nimport asyncio",+ "x = 0\nxx = 1\nawait asyncio.sleep(1)",+ "async def _():\n await asyncio.sleep(x)",+ ]+@staticmethoddef test_get_codes_with_incorrect_args_rets() -> None:app = codegen.get_app(diff --git a/tests/_messaging/test_streams.py b/tests/_messaging/test_streams.pyindex 8e45cf80cf..272039dde4 100644--- a/tests/_messaging/test_streams.py+++ b/tests/_messaging/test_streams.py@@ -8,56 +8,64 @@ from tests.conftest import ExecReqProvider, MockedKernel# just check that its methods are callable and return mocked values.class TestStdin:@staticmethod- def test_encoding(mocked_kernel: MockedKernel) -> None:+ async def test_encoding(mocked_kernel: MockedKernel) -> None:assert mocked_kernel.stdin.encoding == sys.stdin.encoding@staticmethod- def test_input_installed(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run([exec_req.get("output = input('hello')")])+ async def test_input_installed(+ k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run([exec_req.get("output = input('hello')")])assert k.globals["output"] == "hello"@staticmethod- def test_readline_installed(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run([exec_req.get("output = sys.stdin.readline()")])+ async def test_readline_installed(+ k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run([exec_req.get("output = sys.stdin.readline()")])assert k.globals["output"] == ""@staticmethod- def test_readlines_installed(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run([exec_req.get("output = sys.stdin.readlines()")])+ async def test_readlines_installed(+ k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run([exec_req.get("output = sys.stdin.readlines()")])assert k.globals["output"] == [""]class TestStdout:@staticmethod- def test_encoding(mocked_kernel: MockedKernel) -> None:+ async def test_encoding(mocked_kernel: MockedKernel) -> None:assert mocked_kernel.stdout.encoding == sys.stdout.encoding@staticmethod- def test_fileno(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run([exec_req.get("fileno = sys.stdout.fileno()")])+ async def test_fileno(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run([exec_req.get("fileno = sys.stdout.fileno()")])assert k.globals["fileno"] is not None@staticmethod- def test_print(+ async def test_print(mocked_kernel: MockedKernel, exec_req: ExecReqProvider) -> None:- mocked_kernel.k.run([exec_req.get("print('hello'); print('there')")])+ await mocked_kernel.k.run(+ [exec_req.get("print('hello'); print('there')")]+ )assert mocked_kernel.stdout.messages == ["hello", "\n", "there", "\n"]@staticmethod- def test_write(+ async def test_write(mocked_kernel: MockedKernel, exec_req: ExecReqProvider) -> None:- mocked_kernel.k.run(+ await mocked_kernel.k.run([exec_req.get("import sys; sys.stdout.write('hello')")])assert mocked_kernel.stdout.messages == ["hello"]@staticmethod- def test_writelines(+ async def test_writelines(mocked_kernel: MockedKernel, exec_req: ExecReqProvider) -> None:- mocked_kernel.k.run(+ await mocked_kernel.k.run([exec_req.get("import sys; sys.stdout.writelines(['hello', 'there'])"@@ -69,28 +77,28 @@ class TestStdout:class TestStderr:@staticmethod- def test_encoding(mocked_kernel: MockedKernel) -> None:+ async def test_encoding(mocked_kernel: MockedKernel) -> None:assert mocked_kernel.stderr.encoding == sys.stderr.encoding@staticmethod- def test_fileno(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run([exec_req.get("fileno = sys.stderr.fileno()")])+ async def test_fileno(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run([exec_req.get("fileno = sys.stderr.fileno()")])assert k.globals["fileno"] is not None@staticmethod- def test_write(+ async def test_write(mocked_kernel: MockedKernel, exec_req: ExecReqProvider) -> None:- mocked_kernel.k.run(+ await mocked_kernel.k.run([exec_req.get("import sys; sys.stderr.write('hello')")])assert mocked_kernel.stderr.messages == ["hello"]@staticmethod- def test_writelines(+ async def test_writelines(mocked_kernel: MockedKernel, exec_req: ExecReqProvider) -> None:- mocked_kernel.k.run(+ await mocked_kernel.k.run([exec_req.get("import sys; sys.stderr.writelines(['hello', 'there'])"@@ -100,11 +108,11 @@ class TestStderr:assert mocked_kernel.stderr.messages == ["hello", "there"]-def test_import_multiprocessing(+async def test_import_multiprocessing(mocked_kernel: MockedKernel, exec_req: ExecReqProvider) -> None:# https://github.com/marimo-team/marimo/issues/684- mocked_kernel.k.run(+ await mocked_kernel.k.run([exec_req.get("""diff --git a/tests/_plugins/stateless/test_image.py b/tests/_plugins/stateless/test_image.pyindex df9b6969da..7e60355223 100644--- a/tests/_plugins/stateless/test_image.py+++ b/tests/_plugins/stateless/test_image.py@@ -9,15 +9,15 @@ from marimo._runtime.runtime import Kernelfrom tests.conftest import ExecReqProvider-def test_image() -> None:+async def test_image() -> None:result = image("https://marimo.io/logo.png",)assert result.text == "<img src='https://marimo.io/logo.png' />"-def test_image_bytes_io(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_image_bytes_io(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run([exec_req.get("""@@ -34,8 +34,8 @@ def test_image_bytes_io(k: Kernel, exec_req: ExecReqProvider) -> None:assert fname.endswith(".png")-def test_image_bytes(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_image_bytes(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run([exec_req.get("""@@ -52,8 +52,8 @@ def test_image_bytes(k: Kernel, exec_req: ExecReqProvider) -> None:assert fname.endswith(".png")-def test_image_str(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_image_str(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run([exec_req.get("""@@ -68,11 +68,11 @@ def test_image_str(k: Kernel, exec_req: ExecReqProvider) -> None:# TODO(akshayka): Debug on Windows@pytest.mark.skipif(sys.platform == "win32", reason="Failing on Windows CI")-def test_image_local_file(k: Kernel, exec_req: ExecReqProvider) -> None:+async def test_image_local_file(k: Kernel, exec_req: ExecReqProvider) -> None:# Just opens a file that exists, and make sure it gets registered# in the virtual path registrywith open(__file__, encoding="utf-8") as f:- k.run(+ await k.run([exec_req.get(f"""diff --git a/tests/_plugins/ui/_core/test_registry.py b/tests/_plugins/ui/_core/test_registry.pyindex 3741994a88..864baf20d1 100644--- a/tests/_plugins/ui/_core/test_registry.py+++ b/tests/_plugins/ui/_core/test_registry.py@@ -7,10 +7,10 @@ from marimo._runtime.runtime import Kernelfrom tests.conftest import ExecReqProvider-def test_cached_element_still_registered(+async def test_cached_element_still_registered(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+ await k.run([exec_req.get("import functools"),exec_req.get("import marimo as mo"),@@ -30,7 +30,7 @@ def test_cached_element_still_registered(# Re-run the cell but fetch the same slider, since we're using# functools.cache. Make sure it's still registered!- k.run([construct_slider])+ await k.run([construct_slider])assert get_context().ui_element_registry.get_object(s._id) == s@@ -134,8 +134,8 @@ def test_resolve_lens_nested(executing_kernel: Kernel) -> None:)-def test_lens_not_bound(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_lens_not_bound(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run([exec_req.get("""@@ -151,8 +151,10 @@ def test_lens_not_bound(k: Kernel, exec_req: ExecReqProvider) -> None:assert registry.bound_names(array._id) == set(["array"])-def test_parent_bound_to_view(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_parent_bound_to_view(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ await k.run([exec_req.get("""diff --git a/tests/_plugins/ui/_impl/test_altair_chart.py b/tests/_plugins/ui/_impl/test_altair_chart.pyindex ae77f02b85..5150912ce6 100644--- a/tests/_plugins/ui/_impl/test_altair_chart.py+++ b/tests/_plugins/ui/_impl/test_altair_chart.py@@ -108,11 +108,10 @@ class TestAltairChart:assert second == "value2"@staticmethod- def test_altair_settings_when_set(+ async def test_altair_settings_when_set(k: Kernel, exec_req: ExecReqProvider) -> None:-- k.run(+ await k.run([exec_req.get("""diff --git a/tests/_runtime/output/test_output.py b/tests/_runtime/output/test_output.pyindex b0b1c2f6c8..ca0d3d41f3 100644--- a/tests/_runtime/output/test_output.py+++ b/tests/_runtime/output/test_output.py@@ -4,10 +4,10 @@ from __future__ import annotationsfrom tests.conftest import ExecReqProvider, MockedKernel-def test_spinner_removed(+async def test_spinner_removed(mocked_kernel: MockedKernel, exec_req: ExecReqProvider) -> None:- mocked_kernel.k.run(+ await mocked_kernel.k.run([exec_req.get("""@@ -37,13 +37,13 @@ def test_spinner_removed(assert found_progress-def test_mutating_appended_outputs(+async def test_mutating_appended_outputs(mocked_kernel: MockedKernel, exec_req: ExecReqProvider) -> None:# append the same object multiple times, but mutate it in between# appends. make sure the final output message contains the both# versions of the object (before and after mutation)- mocked_kernel.k.run(+ await mocked_kernel.k.run([exec_req.get("""diff --git a/tests/_runtime/test_capture.py b/tests/_runtime/test_capture.pyindex e146405ca7..70ef79bf2b 100644--- a/tests/_runtime/test_capture.py+++ b/tests/_runtime/test_capture.py@@ -20,10 +20,10 @@ def _has_output(return False-def test_capture_stdout(+async def test_capture_stdout(mocked_kernel: MockedKernel, exec_req: ExecReqProvider) -> None:- mocked_kernel.k.run(+ await mocked_kernel.k.run([exec_req.get("""@@ -41,10 +41,10 @@ def test_capture_stdout(assert mocked_kernel.k.globals["buffer"].getvalue() == "hello"-def test_capture_stderr(+async def test_capture_stderr(mocked_kernel: MockedKernel, exec_req: ExecReqProvider) -> None:- mocked_kernel.k.run(+ await mocked_kernel.k.run([exec_req.get("""@@ -62,10 +62,10 @@ def test_capture_stderr(assert mocked_kernel.k.globals["buffer"].getvalue() == "bye"-def test_capture_both(+async def test_capture_both(mocked_kernel: MockedKernel, exec_req: ExecReqProvider) -> None:- mocked_kernel.k.run(+ await mocked_kernel.k.run([# in python < 3.9, parenthesizing multiple context managers is# not allowed, hence the line continuation@@ -87,10 +87,10 @@ def test_capture_both(assert mocked_kernel.k.globals["stderr"].getvalue() == "bye"-def test_redirect_stdout(+async def test_redirect_stdout(mocked_kernel: MockedKernel, exec_req: ExecReqProvider) -> None:- mocked_kernel.k.run(+ await mocked_kernel.k.run([exec_req.get("""@@ -109,10 +109,10 @@ def test_redirect_stdout(assert not _has_output(mocked_kernel.stream.messages, r".*bye.*")-def test_redirect_stderr(+async def test_redirect_stderr(mocked_kernel: MockedKernel, exec_req: ExecReqProvider) -> None:- mocked_kernel.k.run(+ await mocked_kernel.k.run([exec_req.get("""@@ -132,10 +132,10 @@ def test_redirect_stderr(assert not _has_output(mocked_kernel.stream.messages, r".*hello.*")-def test_redirect_both(+async def test_redirect_both(mocked_kernel: MockedKernel, exec_req: ExecReqProvider) -> None:- mocked_kernel.k.run(+ await mocked_kernel.k.run([exec_req.get("""diff --git a/tests/_runtime/test_cell_runner.py b/tests/_runtime/test_cell_runner.pyindex bc1d522e0f..9da717756b 100644--- a/tests/_runtime/test_cell_runner.py+++ b/tests/_runtime/test_cell_runner.py@@ -5,9 +5,9 @@ from marimo._runtime.runtime import Kernelfrom tests.conftest import ExecReqProvider-def test_cell_output(k: Kernel, exec_req: ExecReqProvider) -> None:+async def test_cell_output(k: Kernel, exec_req: ExecReqProvider) -> None:# run the cell to populate the graph, globals- k.run([er := exec_req.get("'hello'; 123")])+ await k.run([er := exec_req.get("'hello'; 123")])runner = Runner(cell_ids=set(k.graph.cells.keys()),@@ -15,19 +15,19 @@ def test_cell_output(k: Kernel, exec_req: ExecReqProvider) -> None:glbls=k.globals,debugger=k.debugger,)- run_result = runner.run(er.cell_id)+ run_result = await runner.run(er.cell_id)# last expression of cell is outputassert run_result.output == 123-def test_traceback_includes_lineno(+async def test_traceback_includes_lineno(k: Kernel, exec_req: ExecReqProvider) -> None:# Raise an exception and test that the runner generates a traceback that# includes the line number where the exception was raised## first run the cell to populate the graph- k.run(+ await k.run([er := exec_req.get("""@@ -45,5 +45,5 @@ def test_traceback_includes_lineno(debugger=k.debugger,)with capture_stderr() as buffer:- runner.run(er.cell_id)+ await runner.run(er.cell_id)assert "line 3" in buffer.getvalue()diff --git a/tests/_runtime/test_control_flow.py b/tests/_runtime/test_control_flow.pyindex 5511bdf084..38e8f7ecdc 100644--- a/tests/_runtime/test_control_flow.py+++ b/tests/_runtime/test_control_flow.py@@ -8,8 +8,8 @@ from marimo._runtime.requests import (from marimo._runtime.runtime import Kernel-def test_stop_false(k: Kernel) -> None:- k.run(+async def test_stop_false(k: Kernel) -> None:+ await k.run([ExecutionRequest(cell_id="0",@@ -23,9 +23,9 @@ def test_stop_false(k: Kernel) -> None:assert k.globals["z"] == 2-def test_stop_true(k: Kernel) -> None:+async def test_stop_true(k: Kernel) -> None:# Populate the kernel and its globals- k.run(+ await k.run([ExecutionRequest(cell_id="0", code="x = 0; y = 1"),ExecutionRequest(cell_id="1", code="z = y + 1"),@@ -36,7 +36,7 @@ def test_stop_true(k: Kernel) -> None:assert k.globals["z"] == 2# Force cell 0 to stop- k.run(+ await k.run([ExecutionRequest(cell_id="0",@@ -52,9 +52,9 @@ def test_stop_true(k: Kernel) -> None:assert "z" not in k.globals-def test_stop_output(k: Kernel) -> None:+async def test_stop_output(k: Kernel) -> None:# Run a cell through the kernel to populate graph- k.run(+ await k.run([ExecutionRequest(cell_id="0",@@ -66,7 +66,7 @@ def test_stop_output(k: Kernel) -> None:runner = cell_runner.Runner(set(["0"]), graph=k.graph, glbls=k.globals, debugger=k.debugger)- run_result = runner.run("0")+ run_result = await runner.run("0")# Check that the cell was stopped and its output is the stop outputassert run_result.output == "stopped!"assert isinstance(run_result.exception, control_flow.MarimoStopError)diff --git a/tests/_runtime/test_marimo_pdb.py b/tests/_runtime/test_marimo_pdb.pyindex 690a723424..4b760a263d 100644--- a/tests/_runtime/test_marimo_pdb.py+++ b/tests/_runtime/test_marimo_pdb.py@@ -3,8 +3,8 @@ from marimo._runtime.runtime import Kernelfrom tests.conftest import ExecReqProvider-def test_pdb_patched(k: Kernel, exec_req: ExecReqProvider):- k.run([exec_req.get("import pdb")])+async def test_pdb_patched(k: Kernel, exec_req: ExecReqProvider):+ await k.run([exec_req.get("import pdb")])pdb = k.globals["pdb"]assert pdb.Pdb == MarimoPdbdiff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex 8c0ab4fbc0..769dc2d0be 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -1,8 +1,11 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import sysfrom typing import Sequence+import pytest+from marimo._messaging.errors import (CycleError,DeleteNonlocalError,@@ -30,11 +33,11 @@ def _check_edges(error: Error, expected_edges: Sequence[Edge]) -> None:# Test Basic Reactivity-def test_triangle(k: Kernel) -> None:+async def test_triangle(k: Kernel) -> None:# x# x --> y# x, y --> z- k.run(+ await k.run([ExecutionRequest(cell_id="0", code="x = 1"),ExecutionRequest(cell_id="1", code="y = x + 1"),@@ -45,53 +48,53 @@ def test_triangle(k: Kernel) -> None:assert k.globals["y"] == 2assert k.globals["z"] == 3- k.run([ExecutionRequest(cell_id="0", code="x = 2")])+ await k.run([ExecutionRequest(cell_id="0", code="x = 2")])assert k.globals["x"] == 2assert k.globals["y"] == 3assert k.globals["z"] == 5- k.run([ExecutionRequest(cell_id="1", code="y = 0")])+ await k.run([ExecutionRequest(cell_id="1", code="y = 0")])assert k.globals["x"] == 2assert k.globals["y"] == 0assert k.globals["z"] == 2- k.delete(DeleteRequest(cell_id="1"))+ await k.delete(DeleteRequest(cell_id="1"))assert k.globals["x"] == 2assert "y" not in k.globalsassert "z" not in k.globals- k.delete(DeleteRequest(cell_id="0"))+ await k.delete(DeleteRequest(cell_id="0"))assert "x" not in k.globalsassert "y" not in k.globalsassert "z" not in k.globals-def test_set_ui_element_value(k: Kernel) -> None:- k.run([ExecutionRequest(cell_id="0", code="import marimo as mo")])- k.run(+async def test_set_ui_element_value(k: Kernel) -> None:+ await k.run([ExecutionRequest(cell_id="0", code="import marimo as mo")])+ await k.run([ExecutionRequest(cell_id="1", code="s = mo.ui.slider(0, 10, value=1); s")])- k.run([ExecutionRequest(cell_id="2", code="x = s.value + 1")])+ await k.run([ExecutionRequest(cell_id="2", code="x = s.value + 1")])assert k.globals["x"] == 2element_id = k.globals["s"]._id- k.set_ui_element_value(SetUIElementValueRequest([(element_id, 5)]))+ await k.set_ui_element_value(SetUIElementValueRequest([(element_id, 5)]))assert k.globals["s"].value == 5assert k.globals["x"] == 6-def test_set_ui_element_value_not_found_doesnt_fail(k: Kernel) -> None:+async def test_set_ui_element_value_not_found_doesnt_fail(k: Kernel) -> None:# smoke test -- this shouldn't raise an exception- k.set_ui_element_value(+ await k.set_ui_element_value(SetUIElementValueRequest([("does not exist", None)]))-def test_set_ui_element_value_lensed(+async def test_set_ui_element_value_lensed(k: Kernel, exec_req: ExecReqProvider) -> None:"""Test setting the value of a lensed element.@@ -99,7 +102,7 @@ def test_set_ui_element_value_lensed(Make sure reactivity flows through its parent, and that its on_changehandler is called exactly once."""- k.run([exec_req.get(code="import marimo as mo")])+ await k.run([exec_req.get(code="import marimo as mo")])# Create an array and output it ...cell_one_code = """@@ -110,15 +113,15 @@ def test_set_ui_element_value_lensed(array = mo.ui.array([mo.ui.slider(0, 10, value=1, on_change=on_change)]);array"""- k.run([exec_req.get(code=cell_one_code)])+ await k.run([exec_req.get(code=cell_one_code)])# Reference the array's value- k.run([exec_req.get(code="x = array.value[0] + 1")])+ await k.run([exec_req.get(code="x = array.value[0] + 1")])assert k.globals["x"] == 2# Set a child of the array to 5 ...child_id = k.globals["array"][0]._id- k.set_ui_element_value(SetUIElementValueRequest([(child_id, 5)]))+ await k.set_ui_element_value(SetUIElementValueRequest([(child_id, 5)]))# Make sure the array and its child are updatedassert k.globals["array"].value == [5]@@ -132,7 +135,7 @@ def test_set_ui_element_value_lensed(assert k.globals["x"] == 6-def test_set_ui_element_value_lensed_bound_child(+async def test_set_ui_element_value_lensed_bound_child(k: Kernel, exec_req: ExecReqProvider) -> None:"""Test setting the value of a lensed element.@@ -140,26 +143,28 @@ def test_set_ui_element_value_lensed_bound_child(Make sure reactivity flows through its parent and also to names boundto children."""- k.run([exec_req.get(code="import marimo as mo")])+ await k.run([exec_req.get(code="import marimo as mo")])cell_one_code = """array = mo.ui.array([mo.ui.slider(0, 10, value=1)])child = array[0]"""- k.run([exec_req.get(code=cell_one_code)])- k.run([exec_req.get(code="x = child.value + 1")])+ await k.run([exec_req.get(code=cell_one_code)])+ await k.run([exec_req.get(code="x = child.value + 1")])array_id = k.globals["array"]._id- k.set_ui_element_value(SetUIElementValueRequest([(array_id, {"0": 5})]))+ await k.set_ui_element_value(+ SetUIElementValueRequest([(array_id, {"0": 5})])+ )assert k.globals["array"].value == [5]assert k.globals["x"] == 6-def test_set_ui_element_value_lensed_with_state(+async def test_set_ui_element_value_lensed_with_state(k: Kernel, exec_req: ExecReqProvider) -> None:"""Test setting the value of a lensed element with on_change set_state"""- k.run([exec_req.get(code="import marimo as mo")])+ await k.run([exec_req.get(code="import marimo as mo")])# Create an array and output it ...cell_one_code = """@@ -170,32 +175,34 @@ def test_set_ui_element_value_lensed_with_state(mo.ui.slider(0, 10, value=1, on_change=set_state)]);"""- k.run([exec_req.get(code=cell_one_code)])- k.run([exec_req.get(code="state = get_state()")])+ await k.run([exec_req.get(code=cell_one_code)])+ await k.run([exec_req.get(code="state = get_state()")])# Set a child of the array and make sure its on_change handler is calledchild_id = k.globals["array"][0]._id- k.set_ui_element_value(SetUIElementValueRequest([(child_id, 5)]))+ await k.set_ui_element_value(SetUIElementValueRequest([(child_id, 5)]))# Make sure the array and its child are updatedassert k.globals["state"] == 5-def test_set_local_var_ui_element_value(k: Kernel) -> None:- k.run([ExecutionRequest("0", "import marimo as mo")])- k.run([ExecutionRequest("1", "_s = mo.ui.slider(0, 10, value=1); _s")])+async def test_set_local_var_ui_element_value(k: Kernel) -> None:+ await k.run([ExecutionRequest("0", "import marimo as mo")])+ await k.run(+ [ExecutionRequest("1", "_s = mo.ui.slider(0, 10, value=1); _s")]+ )# _s's name is mangled to _cell_1_s because it is localassert k.globals["_cell_1_s"].value == 1element_id = k.globals["_cell_1_s"]._id# This shouldn't crash the kernel, and s's value should still be updated- k.set_ui_element_value(SetUIElementValueRequest([(element_id, 5)]))+ await k.set_ui_element_value(SetUIElementValueRequest([(element_id, 5)]))assert k.globals["_cell_1_s"].value == 5-def test_creation_with_ui_element_value(k: Kernel) -> None:+async def test_creation_with_ui_element_value(k: Kernel) -> None:id_provider = IDProvider(prefix="1")- k.instantiate(+ await k.instantiate(CreationRequest(execution_requests=(ExecutionRequest(cell_id="0", code="import marimo as mo"),@@ -212,8 +219,10 @@ def test_creation_with_ui_element_value(k: Kernel) -> None:# Test errors in marimo semantics-def test_kernel_simultaneous_multiple_definition_error(k: Kernel) -> None:- k.run(+async def test_kernel_simultaneous_multiple_definition_error(+ k: Kernel,+) -> None:+ await k.run([ExecutionRequest(cell_id="0", code="x=0"),ExecutionRequest(cell_id="1", code="x=1"),@@ -226,27 +235,29 @@ def test_kernel_simultaneous_multiple_definition_error(k: Kernel) -> None:assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)-def test_kernel_new_multiple_definition_does_not_invalidate(k: Kernel) -> None:- k.run([ExecutionRequest(cell_id="0", code="x=0")])+async def test_kernel_new_multiple_definition_does_not_invalidate(+ k: Kernel,+) -> None:+ await k.run([ExecutionRequest(cell_id="0", code="x=0")])assert k.globals["x"] == 0assert not k.errors# cell 0 should not be invalidated by the introduction of cell 1- k.run([ExecutionRequest(cell_id="1", code="x=0")])+ await k.run([ExecutionRequest(cell_id="1", code="x=0")])assert k.globals["x"] == 0assert set(k.errors.keys()) == {"1"}assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)# re-running cell 0 should invalidate it- k.run([ExecutionRequest(cell_id="0", code="x=0")])+ await k.run([ExecutionRequest(cell_id="0", code="x=0")])assert "x" not in k.globalsassert set(k.errors.keys()) == {"0", "1"}assert k.errors["0"] == (MultipleDefinitionError("x", ("1",)),)assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)-def test_clear_multiple_definition_error(k: Kernel) -> None:- k.run(+async def test_clear_multiple_definition_error(k: Kernel) -> None:+ await k.run([ExecutionRequest(cell_id="0", code="x=0"),ExecutionRequest(cell_id="1", code="x=1"),@@ -259,14 +270,14 @@ def test_clear_multiple_definition_error(k: Kernel) -> None:# Rename second occurrence of x to y; should eliminate error and run both# cells- k.run([ExecutionRequest(cell_id="1", code="y=1")])+ await k.run([ExecutionRequest(cell_id="1", code="y=1")])assert k.globals["x"] == 0assert k.globals["y"] == 1assert not k.errors-def test_clear_multiple_definition_error_with_delete(k: Kernel) -> None:- k.run(+async def test_clear_multiple_definition_error_with_delete(k: Kernel) -> None:+ await k.run([ExecutionRequest(cell_id="0", code="x=0"),ExecutionRequest(cell_id="1", code="x=1"),@@ -278,19 +289,19 @@ def test_clear_multiple_definition_error_with_delete(k: Kernel) -> None:assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)# issue delete request for cell 1 to clear error and run cell 0- k.delete(DeleteRequest(cell_id="1"))+ await k.delete(DeleteRequest(cell_id="1"))assert k.globals["x"] == 0assert not k.errors-def test_new_errors_update_old_ones(k: Kernel) -> None:- k.run([ExecutionRequest(cell_id="0", code="x=0")])- k.run([ExecutionRequest(cell_id="1", code="x, y =1, 2")])+async def test_new_errors_update_old_ones(k: Kernel) -> None:+ await k.run([ExecutionRequest(cell_id="0", code="x=0")])+ await k.run([ExecutionRequest(cell_id="1", code="x, y =1, 2")])assert set(k.errors.keys()) == {"1"}assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)# errors propagated back to cell 1, even though we are not running it- k.run([ExecutionRequest(cell_id="2", code="x, y = 3, 4")])+ await k.run([ExecutionRequest(cell_id="2", code="x, y = 3, 4")])assert set(k.errors.keys()) == {"1", "2"}assert k.errors["1"] == (MultipleDefinitionError("x", ("0", "2")),@@ -304,8 +315,8 @@ def test_new_errors_update_old_ones(k: Kernel) -> None:assert k.globals["x"] == 0-def test_cycle_error(k: Kernel) -> None:- k.run(+async def test_cycle_error(k: Kernel) -> None:+ await k.run([ExecutionRequest(cell_id="0", code="x=y"),ExecutionRequest(cell_id="1", code="y=x"),@@ -321,15 +332,15 @@ def test_cycle_error(k: Kernel) -> None:_check_edges(k.errors["1"][0], [("0", "1"), ("1", "0")])# break cycle by modifying cell- k.run([ExecutionRequest(cell_id="1", code="y=1")])+ await k.run([ExecutionRequest(cell_id="1", code="y=1")])assert k.globals["x"] == 1assert k.globals["y"] == 1assert k.globals["z"] == 2assert not k.errors-def test_break_cycle_error_with_delete(k: Kernel) -> None:- k.run(+async def test_break_cycle_error_with_delete(k: Kernel) -> None:+ await k.run([ExecutionRequest(cell_id="0", code="x=y"),ExecutionRequest(cell_id="1", code="y=x"),@@ -343,12 +354,12 @@ def test_break_cycle_error_with_delete(k: Kernel) -> None:_check_edges(k.errors["0"][0], [("0", "1"), ("1", "0")])# break cycle by deleting cell- k.delete(DeleteRequest(cell_id="1"))+ await k.delete(DeleteRequest(cell_id="1"))assert not k.errors-def test_delete_nonlocal_error(k: Kernel) -> None:- k.run(+async def test_delete_nonlocal_error(k: Kernel) -> None:+ await k.run([ExecutionRequest(cell_id="0", code="x=0"),ExecutionRequest(cell_id="1", code="del x; y = 1"),@@ -361,14 +372,14 @@ def test_delete_nonlocal_error(k: Kernel) -> None:assert k.errors["1"] == (DeleteNonlocalError("x", ("0",)),)# fix cell 1, should run cell 1 and 2- k.run([ExecutionRequest(cell_id="1", code="y=1")])+ await k.run([ExecutionRequest(cell_id="1", code="y=1")])assert k.globals["y"] == 1assert k.globals["z"] == 2assert not k.errors-def test_defs_with_no_definers_are_removed_from_cell(k: Kernel) -> None:- k.run(+async def test_defs_with_no_definers_are_removed_from_cell(k: Kernel) -> None:+ await k.run([ExecutionRequest(cell_id="0", code="x=0"),ExecutionRequest(cell_id="1", code="del x"),@@ -379,27 +390,27 @@ def test_defs_with_no_definers_are_removed_from_cell(k: Kernel) -> None:# Delete the cell that defines x. There shouldn't be any more errors# because x no longer exists.- k.delete(DeleteRequest(cell_id="0"))+ await k.delete(DeleteRequest(cell_id="0"))assert not k.errors# Add x back in.- k.run([ExecutionRequest(cell_id="2", code="x=0")])+ await k.run([ExecutionRequest(cell_id="2", code="x=0")])assert set(k.errors.keys()) == {"1"}assert k.errors["1"] == (DeleteNonlocalError("x", ("2",)),)# Repair graph- k.run([ExecutionRequest(cell_id="1", code="y = x + 1")])+ await k.run([ExecutionRequest(cell_id="1", code="y = x + 1")])assert not k.errorsassert k.globals["y"] == 1# Make sure graph is tracking x again and update propagates- k.run([ExecutionRequest(cell_id="2", code="x = 1")])+ await k.run([ExecutionRequest(cell_id="2", code="x = 1")])assert not k.errorsassert k.globals["y"] == 2-def test_syntax_error(k: Kernel) -> None:- k.run(+async def test_syntax_error(k: Kernel) -> None:+ await k.run([ExecutionRequest(cell_id="0", code="x=0"),ExecutionRequest(cell_id="1", code="x; y = 1"),@@ -409,14 +420,14 @@ def test_syntax_error(k: Kernel) -> None:assert k.globals["y"] == 1assert not k.errors- k.run([ExecutionRequest(cell_id="0", code="x=")])+ await k.run([ExecutionRequest(cell_id="0", code="x=")])assert "x" not in k.globalsassert "y" not in k.globalsassert "0" not in k.graph.cellsassert "1" in k.graph.cells# fix syntax error- k.run([ExecutionRequest(cell_id="0", code="x=0")])+ await k.run([ExecutionRequest(cell_id="0", code="x=0")])assert k.globals["x"] == 0assert k.globals["y"] == 1assert "0" in k.graph.cells@@ -424,10 +435,10 @@ def test_syntax_error(k: Kernel) -> None:assert not k.errors-def test_disable_and_reenable_not_stale(+async def test_disable_and_reenable_not_stale(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+ await k.run([(er_1 := exec_req.get(@@ -449,7 +460,7 @@ def test_disable_and_reenable_not_stale(# disable and re-enable cell 2: cell 2 should not re-run because it# shouldn't have passed through stale status# disable cell 2- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}}))assert k.globals["ns"].count == 1@@ -457,7 +468,7 @@ def test_disable_and_reenable_not_stale(assert not k.graph.cells[er_2.cell_id].stale# re-enable cell 2- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_2.cell_id: {"disabled": False}}))# cell 2 should **not** have re-run@@ -466,10 +477,10 @@ def test_disable_and_reenable_not_stale(assert not k.graph.cells[er_2.cell_id].stale-def test_disable_and_reenable_stale(+async def test_disable_and_reenable_stale(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+ await k.run([(er_1 := exec_req.get(@@ -490,10 +501,10 @@ def test_disable_and_reenable_stale(# disable and re-enable cell 2, making it stale in between;# cell 2 should re-run on enable- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}}))- k.run(+ await k.run([exec_req.get_with_id(er_1.cell_id,@@ -512,7 +523,7 @@ def test_disable_and_reenable_stale(assert k.graph.cells[er_2.cell_id].stale# re-enable cell 2- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_2.cell_id: {"disabled": False}}))# cell 2 should have re-run@@ -521,13 +532,13 @@ def test_disable_and_reenable_stale(assert not k.graph.cells[er_2.cell_id].stale-def test_disable_and_reenable_tree(+async def test_disable_and_reenable_tree(k: Kernel, exec_req: ExecReqProvider) -> None:# x# x --> y# x, y --> z- k.run(+ await k.run([(er_1 := exec_req.get("x = 1")),(er_2 := exec_req.get("y = x + 1")),@@ -549,11 +560,11 @@ def test_disable_and_reenable_tree(assert not k.graph.cells[er_5.cell_id].stale# disable cell 2- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}}))- k.run([ExecutionRequest(cell_id=er_1.cell_id, code="x = 2")])+ await k.run([ExecutionRequest(cell_id=er_1.cell_id, code="x = 2")])assert k.globals["x"] == 2assert k.globals["zzz"] == 3@@ -574,7 +585,7 @@ def test_disable_and_reenable_tree(assert not k.graph.cells[er_5.cell_id].stale# enable cell 2: should run stale cells as a side-effect- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_2.cell_id: {"disabled": False}}))assert k.globals["x"] == 2@@ -592,8 +603,10 @@ def test_disable_and_reenable_tree(assert not k.graph.cells[er_5.cell_id].stale-def test_disable_consecutive(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_disable_consecutive(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ await k.run([(er_1 := exec_req.get("x = 1")),(er_2 := exec_req.get("y = x + 1")),@@ -605,21 +618,21 @@ def test_disable_consecutive(k: Kernel, exec_req: ExecReqProvider) -> None:assert not k.graph.cells[er_2.cell_id].stale# disable both cells- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}}))- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}}))# update the code of cell 1 -- both cells stale- k.run([exec_req.get_with_id(er_1.cell_id, "x = 2")])+ await k.run([exec_req.get_with_id(er_1.cell_id, "x = 2")])assert "x" not in k.globalsassert "y" not in k.globalsassert k.graph.cells[er_1.cell_id].staleassert k.graph.cells[er_2.cell_id].stale# enable cell 1, but 2 still disabled- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_1.cell_id: {"disabled": False}}))assert k.globals["x"] == 2@@ -628,7 +641,7 @@ def test_disable_consecutive(k: Kernel, exec_req: ExecReqProvider) -> None:assert k.graph.cells[er_2.cell_id].stale# enable cell 2- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_2.cell_id: {"disabled": False}}))assert k.globals["x"] == 2@@ -637,8 +650,10 @@ def test_disable_consecutive(k: Kernel, exec_req: ExecReqProvider) -> None:assert not k.graph.cells[er_2.cell_id].stale-def test_disable_syntax_error(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_disable_syntax_error(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ await k.run([(er_1 := exec_req.get("x = 1")),]@@ -646,110 +661,110 @@ def test_disable_syntax_error(k: Kernel, exec_req: ExecReqProvider) -> None:assert k.globals["x"] == 1# disable cell- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}}))# add a syntax error- k.run([exec_req.get_with_id(er_1.cell_id, "x 2")])+ await k.run([exec_req.get_with_id(er_1.cell_id, "x 2")])assert "x" not in k.globals# repair syntax, cell should still be disabled- k.run([exec_req.get_with_id(er_1.cell_id, "x = 2")])+ await k.run([exec_req.get_with_id(er_1.cell_id, "x = 2")])assert "x" not in k.globalsassert k.graph.cells[er_1.cell_id].stale# enable: should run- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_1.cell_id: {"disabled": False}}))assert k.globals["x"] == 2assert not k.graph.cells[er_1.cell_id].stale-def test_disable_cycle(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_disable_cycle(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run([(er_1 := exec_req.get("a = b")),(er_2 := exec_req.get("b = a")),])- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}}))assert k.graph.cells[er_1.cell_id].config.disabledassert k.graph.cells[er_2.cell_id].disabled_transitively- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}}))- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_1.cell_id: {"disabled": False}}))assert k.graph.cells[er_1.cell_id].disabled_transitivelyassert k.graph.cells[er_2.cell_id].config.disabled# adding a new cell shouldn't toggle disabled states of either- k.run([exec_req.get("c = 0")])+ await k.run([exec_req.get("c = 0")])assert k.graph.cells[er_1.cell_id].disabled_transitivelyassert k.graph.cells[er_2.cell_id].config.disabled# breaking the cycle should re-enable- k.run([ExecutionRequest(cell_id=er_1.cell_id, code="a = 0")])+ await k.run([ExecutionRequest(cell_id=er_1.cell_id, code="a = 0")])assert not k.graph.cells[er_1.cell_id].disabled_transitivelyassert not k.graph.cells[er_1.cell_id].staleassert not k.graph.cells[er_1.cell_id].config.disabledassert k.graph.cells[er_2.cell_id].config.disabled-def test_disable_cycle_incremental(+async def test_disable_cycle_incremental(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run([er_1 := exec_req.get("a = b")])- k.set_cell_config(+ await k.run([er_1 := exec_req.get("a = b")])+ await k.set_cell_config(SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}}))assert k.graph.cells[er_1.cell_id].config.disabled- k.run([er_2 := exec_req.get("b = a")])+ await k.run([er_2 := exec_req.get("b = a")])assert k.graph.cells[er_2.cell_id].disabled_transitively-def test_enable_cycle_incremental(+async def test_enable_cycle_incremental(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+ await k.run([(er_1 := exec_req.get("a = b")),(er_2 := exec_req.get("b = a")),])- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}}))assert k.graph.cells[er_1.cell_id].config.disabledassert k.graph.cells[er_2.cell_id].disabled_transitively- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_1.cell_id: {"disabled": False}}))assert not k.graph.cells[er_1.cell_id].config.disabledassert k.graph.cells[er_2.cell_id].status == "idle"-def test_set_config_before_registering_cell(+async def test_set_config_before_registering_cell(k: Kernel, exec_req: ExecReqProvider) -> None:er_1 = exec_req.get("x = 0")- k.set_cell_config(+ await k.set_cell_config(SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}}))- k.run([er_1])+ await k.run([er_1])assert k.graph.cells[er_1.cell_id].config.disabledassert "x" not in k.globals-def test_interrupt(k: Kernel, exec_req: ExecReqProvider) -> None:+async def test_interrupt(k: Kernel, exec_req: ExecReqProvider) -> None:er = exec_req.get("""from marimo._runtime.control_flow import MarimoInterrupt@@ -763,14 +778,14 @@ def test_interrupt(k: Kernel, exec_req: ExecReqProvider) -> None:tries += 1""")- k.run([er])+ await k.run([er])# make sure the interrupt wasn't caught by the try/exceptassert k.globals["tries"] == 0-def test_file_path(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_file_path(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run([exec_req.get("import marimo as mo"),exec_req.get("x = __file__"),@@ -780,8 +795,10 @@ def test_file_path(k: Kernel, exec_req: ExecReqProvider) -> None:assert "pytest" in k.globals["x"]-def test_cell_state_invalidated(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_cell_state_invalidated(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ await k.run([(er_1 := exec_req.get("x = 0")),(exec_req.get("x; y = 1")),@@ -791,12 +808,12 @@ def test_cell_state_invalidated(k: Kernel, exec_req: ExecReqProvider) -> None:# "y" should not have run, and its global state should have been# invalidated- k.run([ExecutionRequest(er_1.cell_id, "x = 0; raise RuntimeError")])+ await k.run([ExecutionRequest(er_1.cell_id, "x = 0; raise RuntimeError")])assert "y" not in k.globals-def test_pickle(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_pickle(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run([exec_req.get("import pickle"),exec_req.get(@@ -811,3 +828,211 @@ def test_pickle(k: Kernel, exec_req: ExecReqProvider) -> None:])assert k.globals["pickle_output"] is not None+++class TestAsyncIO:+ @staticmethod+ async def test_toplevel_await_allowed(+ k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run(+ [+ exec_req.get(+ """+ import asyncio+ await asyncio.sleep(0)+ ran = True+ """+ ),+ ]+ )+ assert k.globals["ran"]++ @staticmethod+ async def test_toplevel_gather(+ k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run(+ [+ exec_req.get(+ """+ l = []+ async def f():+ l.append(1)+ await asyncio.sleep(0.1)+ l.append(2)++ import asyncio+ await asyncio.gather(f(), f())+ """+ ),+ ]+ )+ assert k.globals["l"] == [1, 1, 2, 2]++ @staticmethod+ async def test_wait_for(k: Kernel, exec_req: ExecReqProvider) -> None:+ import asyncio++ await k.run(+ [+ exec_req.get(+ """+ import asyncio+ async def eternity():+ await asyncio.sleep(3600)++ e = None+ try:+ await asyncio.wait_for(eternity(), timeout=0)+ except asyncio.exceptions.TimeoutError as exc:+ e = exc+ """+ ),+ ]+ )+ assert not k.errors+ assert isinstance(k.globals["e"], asyncio.exceptions.TimeoutError)++ @staticmethod+ async def test_await_future(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run(+ [+ exec_req.get(+ """+ import asyncio+ future = asyncio.Future()+ future.set_result(1)+ """+ ),+ exec_req.get(+ """+ result = await future+ """+ ),+ ]+ )+ assert k.globals["result"] == 1+ assert k.globals["future"].done()++ @staticmethod+ async def test_await_future_complex(+ k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run(+ [+ exec_req.get(+ """+ import asyncio+ """+ ),+ exec_req.get(+ """+ async def set_after(fut, delay, value):+ await asyncio.sleep(delay)+ fut.set_result(value)+ """+ ),+ exec_req.get(+ """+ fut = asyncio.Future()+ asyncio.create_task(set_after(fut, 0.01, "done"))+ result = await fut+ """+ ),+ ]+ )+ assert k.globals["result"] == "done"++ @staticmethod+ async def test_run_in_default_executor(+ k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run(+ [+ exec_req.get(+ """+ import asyncio+ """+ ),+ exec_req.get(+ """+ def blocking():+ return "done"+ """+ ),+ exec_req.get(+ """+ res = await asyncio.get_running_loop().run_in_executor(+ None, blocking)+ """+ ),+ ]+ )+ assert k.globals["res"] == "done"++ @staticmethod+ async def test_run_in_threadpool_executor(+ k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run(+ [+ exec_req.get(+ """+ import asyncio+ import concurrent.futures+ """+ ),+ exec_req.get(+ """+ def blocking():+ return "done"+ """+ ),+ exec_req.get(+ """+ loop = asyncio.get_running_loop()+ with concurrent.futures.ThreadPoolExecutor() as pool:+ res = await loop.run_in_executor(pool, blocking)+ """+ ),+ ]+ )+ assert k.globals["res"] == "done"++ @staticmethod+ @pytest.mark.xfail(+ condition=sys.platform == "win32" or sys.platform == "darwin",+ reason=(+ "Bug in interaction with multiprocessing on Windows, macOS; "+ "doesn't work in Jupyter either."+ ),+ )+ async def test_run_in_processpool_executor(+ k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run(+ [+ exec_req.get(+ """+ import asyncio+ import concurrent.futures+ """+ ),+ exec_req.get(+ """+ def blocking():+ return "done"+ """+ ),+ exec_req.get(+ """+ loop = asyncio.get_running_loop()+ with concurrent.futures.ProcessPoolExecutor() as pool:+ res = await loop.run_in_executor(pool, blocking)+ """+ ),+ ]+ )+ assert not k.errors+ assert k.globals["res"] == "done"diff --git a/tests/_runtime/test_state.py b/tests/_runtime/test_state.pyindex 75a4dac46e..463df7405a 100644--- a/tests/_runtime/test_state.py+++ b/tests/_runtime/test_state.py@@ -3,8 +3,8 @@ from marimo._runtime.runtime import Kernelfrom tests.conftest import ExecReqProvider-def test_set_and_get_state(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_set_and_get_state(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run([exec_req.get("import marimo as mo"),exec_req.get("state, set_state = mo.state(0)"),@@ -22,8 +22,10 @@ def test_set_and_get_state(k: Kernel, exec_req: ExecReqProvider) -> None:assert k.globals["x"] == 1-def test_set_and_get_iteration(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_set_and_get_iteration(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ await k.run([exec_req.get("import marimo as mo"),exec_req.get("state, set_state = mo.state(0)"),@@ -41,8 +43,8 @@ def test_set_and_get_iteration(k: Kernel, exec_req: ExecReqProvider) -> None:assert k.globals["x"] == 5-def test_no_self_loops(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_no_self_loops(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run([exec_req.get("import marimo as mo"),exec_req.get("state, set_state = mo.state(0)"),@@ -53,8 +55,8 @@ def test_no_self_loops(k: Kernel, exec_req: ExecReqProvider) -> None:assert k.globals["x"] == 0-def test_allow_self_loops(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_allow_self_loops(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run([exec_req.get("import marimo as mo"),exec_req.get(@@ -73,8 +75,10 @@ def test_allow_self_loops(k: Kernel, exec_req: ExecReqProvider) -> None:assert k.globals["x"] == 3-def test_update_with_function(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_update_with_function(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ await k.run([exec_req.get("import marimo as mo"),exec_req.get("state, set_state = mo.state(0)"),@@ -86,8 +90,10 @@ def test_update_with_function(k: Kernel, exec_req: ExecReqProvider) -> None:assert k.globals["x"] == 1-def test_set_to_callable_object(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_set_to_callable_object(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ await k.run([exec_req.get("import marimo as mo"),exec_req.get("state, set_state = mo.state(0)"),@@ -109,8 +115,8 @@ def test_set_to_callable_object(k: Kernel, exec_req: ExecReqProvider) -> None:assert not k.globals["x"].called-def test_non_stale_not_run(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_non_stale_not_run(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run([exec_req.get("import marimo as mo"),exec_req.get(@@ -132,8 +138,8 @@ def test_non_stale_not_run(k: Kernel, exec_req: ExecReqProvider) -> None:assert k.globals["private"].counter == 1-def test_cancelled_not_run(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_cancelled_not_run(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run([exec_req.get("import marimo as mo"),exec_req.get("state, set_state = mo.state(0)"),@@ -147,7 +153,7 @@ def test_cancelled_not_run(k: Kernel, exec_req: ExecReqProvider) -> None:assert "y" not in k.globals-def test_set_state_with_overridden_eq(+async def test_set_state_with_overridden_eq(k: Kernel, exec_req: ExecReqProvider) -> None:create_class = """@@ -158,7 +164,7 @@ def test_set_state_with_overridden_eq(sys.exit()a = A()"""- k.run(+ await k.run([exec_req.get("import marimo as mo"),exec_req.get(create_class),diff --git a/tests/_runtime/test_virtual_file.py b/tests/_runtime/test_virtual_file.pyindex 301b002169..7498340574 100644--- a/tests/_runtime/test_virtual_file.py+++ b/tests/_runtime/test_virtual_file.py@@ -7,8 +7,10 @@ from marimo._runtime.runtime import Kernelfrom tests.conftest import ExecReqProvider-def test_virtual_file_creation(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_virtual_file_creation(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ await k.run([exec_req.get("""@@ -25,8 +27,10 @@ def test_virtual_file_creation(k: Kernel, exec_req: ExecReqProvider) -> None:assert fname.endswith(".pdf")-def test_virtual_file_deletion(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_virtual_file_deletion(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ await k.run([er := exec_req.get("""@@ -42,14 +46,14 @@ def test_virtual_file_deletion(k: Kernel, exec_req: ExecReqProvider) -> None:for fname, _ in get_context().virtual_file_registry.registry.items():assert fname.endswith(".pdf")- k.delete(DeleteRequest(cell_id=er.cell_id))+ await k.delete(DeleteRequest(cell_id=er.cell_id))assert not get_context().virtual_file_registry.registry-def test_cached_virtual_file_not_deleted(+async def test_cached_virtual_file_not_deleted(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+ await k.run([exec_req.get("""@@ -74,25 +78,25 @@ def test_cached_virtual_file_not_deleted(# Rerun the cell that created the vfile: make sure that the vfile# still exists- k.run([create_vfile_1])+ await k.run([create_vfile_1])assert len(get_context().virtual_file_registry.registry) == 1# Create a new vfile, make sure we have two now- k.run([create_vfile_2 := exec_req.get("create_vfile(2)")])+ await k.run([create_vfile_2 := exec_req.get("create_vfile(2)")])assert len(get_context().virtual_file_registry.registry) == 2# Remove the cells that create the vfiles- k.delete(DeleteRequest(cell_id=create_vfile_1.cell_id))- k.delete(DeleteRequest(cell_id=create_vfile_2.cell_id))+ await k.delete(DeleteRequest(cell_id=create_vfile_1.cell_id))+ await k.delete(DeleteRequest(cell_id=create_vfile_2.cell_id))# Reset the vfile cache- k.run([vfile_cache])+ await k.run([vfile_cache])-def test_cell_deletion_clears_vfiles(+async def test_cell_deletion_clears_vfiles(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+ await k.run([exec_req.get("""@@ -116,14 +120,14 @@ def test_cell_deletion_clears_vfiles(assert len(get_context().virtual_file_registry.registry) == 1# Delete the vfile cache: virtual file registry should be empty- k.delete(DeleteRequest(cell_id=vfile_cache.cell_id))+ await k.delete(DeleteRequest(cell_id=vfile_cache.cell_id))assert len(get_context().virtual_file_registry.registry) == 0-def test_vfile_refcount_incremented(+async def test_vfile_refcount_incremented(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+ await k.run([exec_req.get("""@@ -154,10 +158,10 @@ def test_vfile_refcount_incremented(assert get_context().virtual_file_registry.refcount(vfile) == 2-def test_vfile_refcount_decremented(+async def test_vfile_refcount_decremented(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+ await k.run([exec_req.get("""@@ -185,19 +189,21 @@ def test_vfile_refcount_decremented(# 0 references because HTML not bound to a variable# NB: this test may be flaky! refcount decremented when `__del__` is called# but we can't rely on when it will be called.- k.run([exec_req.get("gc.collect()")])+ await k.run([exec_req.get("gc.collect()")])assert ctx.virtual_file_registry.refcount(vfile) == 0# this should dispose the old vfile (because its refcount is 0) and create# a new one- k.run([make_vfile])+ await k.run([make_vfile])# the previous vfile should not be in the registryassert vfile not in ctx.virtual_file_registry.registryassert len(ctx.virtual_file_registry.registry) == 1-def test_cached_vfile_disposal(k: Kernel, exec_req: ExecReqProvider) -> None:- k.run(+async def test_cached_vfile_disposal(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ await k.run([exec_req.get("""@@ -226,13 +232,13 @@ def test_cached_vfile_disposal(k: Kernel, exec_req: ExecReqProvider) -> None:assert ctx.virtual_file_registry.refcount(vfile) == 1# clear the list, refcount should be decremented- k.run([exec_req.get("vfiles[:] = []")])+ await k.run([exec_req.get("vfiles[:] = []")])# NB: this test may be flaky! refcount decremented when `__del__` is called# but we can't rely on when it will be called.- k.run([exec_req.get("import gc; gc.collect()")])+ await k.run([exec_req.get("import gc; gc.collect()")])assert ctx.virtual_file_registry.refcount(vfile) == 0# create another vfile. the old one should be deleted- k.run([append_vfile])+ await k.run([append_vfile])assert len(ctx.virtual_file_registry.registry) == 1assert vfile not in ctx.virtual_file_registry.filenames()