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: mo.thread lifecycle (#4782)
Akshay Agrawal2b8e2fc68644
diff --git a/docs/api/control_flow.md b/docs/api/control_flow.mdindex cfec9fdb64..5110639e23 100644--- a/docs/api/control_flow.md+++ b/docs/api/control_flow.md@@ -1,9 +1,19 @@# Control flow-Use `mo.stop` to halt execution of a cell, and optionally output an object.-This function is useful for validating user input.+## Controlling when cells run++* Use [`mo.stop`][marimo.stop] to halt execution of a cell when a condition is met.+* Combine [`mo.stop`][marimo.stop] with [`mo.ui.run_button`][marimo.ui.run_button] to gate execution on button click.+* Use [`mo.ui.refresh`][marimo.ui.refresh] to make cells run periodically.++!!! tip "Lazy execution"++ In addition to these utilities, you can [configure the runtime to be lazy](../guides/expensive_notebooks.md#configure-how-marimo-runs-cells), marking cells as stale instead of automatically running them.::: marimo.stop-Use [`mo.ui.refresh`][marimo.ui.refresh] to trigger other cells to run periodically, on a configurable-interval (or on click).+## Threading++::: marimo.Thread++::: marimo.current_threaddiff --git a/docs/api/miscellaneous.md b/docs/api/miscellaneous.mdindex 862733f112..f5687abe83 100644--- a/docs/api/miscellaneous.md+++ b/docs/api/miscellaneous.md@@ -9,5 +9,3 @@::: marimo.notebook_dir::: marimo.notebook_location--::: marimo.Threaddiff --git a/docs/guides/outputs.md b/docs/guides/outputs.mdindex 2d0853e84d..eefa8bc6a1 100644--- a/docs/guides/outputs.md+++ b/docs/guides/outputs.md@@ -200,6 +200,28 @@ To create a thread that can reliably communicate outputs to the frontend,use [`mo.Thread`][marimo.Thread], which has exactly the same API asas `threading.Thread`.+### Cleaning up your thread++When the cell that spawned a [`mo.Thread`][marimo.Thread] is invalidated+(re-run, deleted, interrupted, or otherwise errored), the thread's+`should_exit` property will evaluate to `True`, at which point it is your+responsibility to clean up your thread. You can retrieve the current+[`mo.Thread`][marimo.Thread] with [`mo.current_thread`][marimo.current_thread].++**Example.**++```python+def target():+ import marimo as mo++ thread = mo.current_thread()+ while not thread.should_exit:+ ...+```+++### Patching threads created by third-party code+If you need to forward outputs from threads spawned by third-party code, trypatching `threading.Thread`:@@ -209,3 +231,6 @@ import marimo as mothreading.Thread = mo.Thread```++This however may leak threads, since the patched threads won't know to check the `mo.Thread`'s+`should_exit` property.diff --git a/marimo/__init__.py b/marimo/__init__.pyindex f926d434c3..678144e0e3 100644--- a/marimo/__init__.py+++ b/marimo/__init__.py@@ -22,6 +22,7 @@ __all__ = ["MarimoIslandGenerator","MarimoStopError","Thread",+ "current_thread",# Other namespaces"ai","ui",@@ -137,7 +138,7 @@ from marimo._runtime.runtime import (refs,)from marimo._runtime.state import state-from marimo._runtime.threads import Thread+from marimo._runtime.threads import Thread, current_threadfrom marimo._save.save import cache, lru_cache, persistent_cachefrom marimo._server.asgi import create_asgi_appfrom marimo._sql.sql import sqldiff --git a/marimo/_runtime/threads.py b/marimo/_runtime/threads.pyindex f57adda8a6..2465393b9c 100644--- a/marimo/_runtime/threads.py+++ b/marimo/_runtime/threads.py@@ -5,6 +5,7 @@ import threadingfrom typing import Anyfrom marimo._messaging.streams import ThreadSafeStream+from marimo._runtime.cell_lifecycle_item import CellLifecycleItemfrom marimo._runtime.context.kernel_context import KernelRuntimeContextfrom marimo._runtime.context.script_context import ScriptRuntimeContextfrom marimo._runtime.context.types import (@@ -21,7 +22,7 @@ THREADS = set()class Thread(threading.Thread):- """A Thread subclass that is aware of marimo internals.+ """A Thread subclass that can communicate with the frontend.`mo.Thread` has the same API as threading.Thread,but `mo.Thread`s are able to communicate with the marimo@@ -33,17 +34,55 @@ class Thread(threading.Thread):Writing directly to sys.stdout or sys.stderr, or to file descriptors 1 and2, is not yet supported.++ **Thread lifecycle.** When the cell that spawned this thread is invalidated+ (re-run, deleted, interrupted, or otherwise errored), this thread's+ `should_exit` property will evaluate to `True`, at which point it+ is the developer's responsibility to clean up their thread.++ **Example.**++ ```python+ def target():+ import time+ import marimo as mo++ thread = mo.current_thread()+ while not thread.should_exit:+ time.sleep(1)+ print("hello")+ ```++ ```python+ import marimo as mo++ mo.Thread(target=target).start()+ ```"""def __init__(self, *args: Any, **kwargs: Any) -> None:super().__init__(*args, **kwargs)self._marimo_ctx: RuntimeContext | None = None+ exit_event = threading.Event()+ self._exit_event = exit_eventif not runtime_context_installed():return+ class ThreadLifecycle(CellLifecycleItem):+ def create(self, context: RuntimeContext) -> None:+ del context++ def dispose(self, context: RuntimeContext, deletion: bool) -> bool:+ del context+ del deletion+ exit_event.set()+ return True+ctx = get_context()+ ctx.cell_lifecycle_registry.add(ThreadLifecycle())+if isinstance(ctx, KernelRuntimeContext):self._marimo_ctx = KernelRuntimeContext(**ctx.__dict__)# standard IO is not yet threadsafe@@ -77,6 +116,30 @@ class Thread(threading.Thread):"Unsupported stream type " + str(type(ctx.stream)))+ @property+ def should_exit(self) -> bool:+ """Whether this thread should exit.++ Returns `True` when the cell that spawned this thread has been invalidated;+ for example, if the cell:++ - was re-run+ - was deleted+ - was interrupted++ then this property evaluates to True.++ It is the developer's responsibility to clean up and finish their+ thread when this flag is set. Retrieve the current `mo.Thread` with++ ```python+ import marimo as mo++ mo.current_thread()+ ```+ """+ return self._exit_event.is_set()+def run(self) -> None:if self._marimo_ctx is not None:initialize_context(self._marimo_ctx)@@ -90,3 +153,21 @@ class Thread(threading.Thread):super().run()THREADS.remove(thread_id)teardown_context()+++def current_thread() -> Thread:+ """Return the `marimo.Thread` object for the caller's thread of control.++ Returns:+ The current `marimo.Thread` object.++ Raises:+ RuntimeError: If the current thread of control is not a `marimo.Thread`.+ """+ thread = threading.current_thread()+ if not isinstance(thread, Thread):+ raise RuntimeError(+ "mo.current_thread() must be called from a "+ "thread created with mo.Thread."+ )+ return threaddiff --git a/tests/_runtime/test_threads.py b/tests/_runtime/test_threads.pyindex 4bea4dc5ec..7df085ef68 100644--- a/tests/_runtime/test_threads.py+++ b/tests/_runtime/test_threads.py@@ -1,5 +1,6 @@import time+from marimo._runtime.requests import DeleteCellRequestfrom marimo._runtime.runtime import Kernelfrom tests.conftest import ExecReqProvider@@ -135,3 +136,101 @@ async def test_thread_print(k: Kernel, exec_req: ExecReqProvider) -> None:assert thread_stream.messages[0][1]["console"]["channel"] == "stdout"assert "world" in thread_stream.messages[1][1]["console"]["data"]assert thread_stream.messages[1][1]["console"]["channel"] == "stdout"+++async def test_thread_should_exit_on_rerun(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ """Test that a thread's exit event is set when cell lifecycle is disposed."""++ await k.run(+ [+ exec_req.get("import marimo as mo"),+ exec_req.get(+ """+ def target():+ ...+ """+ ),+ er := exec_req.get(+ """+ thread = mo.Thread(target=target)+ thread.start()+ """+ ),+ ]+ )++ thread = k.globals["thread"]+ assert not thread.should_exit++ # rerunning the cell should trigger the cell lifecycle disposal and set its exit event+ await k.run([er])+ assert thread.should_exit+++async def test_thread_should_not_exit_on_other_cell_run(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ """Test that a thread's exit event is set when cell lifecycle is disposed."""++ await k.run(+ [+ exec_req.get("import marimo as mo"),+ exec_req.get(+ """+ def target():+ ...+ """+ ),+ exec_req.get(+ """+ thread = mo.Thread(target=target)+ thread.start()+ """+ ),+ er := exec_req.get(+ """+ ...+ """+ ),+ ]+ )++ thread = k.globals["thread"]+ assert not thread.should_exit++ # rerunning a cell that is not related to the spawning cell should _not_+ # signal the thread to exit+ await k.run([er])+ assert not thread.should_exit+++async def test_thread_should_exit_on_deletion(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ """Test that a thread's exit event is set when cell lifecycle is disposed."""++ await k.run(+ [+ exec_req.get("import marimo as mo"),+ exec_req.get(+ """+ def target():+ ...+ """+ ),+ er := exec_req.get(+ """+ thread = mo.Thread(target=target)+ thread.start()+ """+ ),+ ]+ )++ thread = k.globals["thread"]+ assert not thread.should_exit++ await k.delete_cell(DeleteCellRequest(er.cell_id))+ assert thread.should_exitdiff --git a/tests/snapshots/api.txt b/tests/snapshots/api.txtindex ebf1e71795..aa6bc64abd 100644--- a/tests/snapshots/api.txt+++ b/tests/snapshots/api.txt@@ -25,6 +25,7 @@ carouselcentercli_argscreate_asgi_app+current_threaddefsdocdownload