Skip to content

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.

fix: mo.Thread communication to output area (#3611)

Akshay Agrawal0d719dd64756
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index f5deeadc85..68e8f70119 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -364,7 +364,7 @@ def _launch_pyodide_kernel(
debugger_override=debugger,
user_config=user_config,
)
- initialize_kernel_context(
+ ctx = initialize_kernel_context(
kernel=kernel,
stream=stream,
stdout=stdout,
@@ -374,9 +374,7 @@ def _launch_pyodide_kernel(
)
if is_edit_mode:
- signal.signal(
- signal.SIGINT, handlers.construct_interrupt_handler(kernel)
- )
+ signal.signal(signal.SIGINT, handlers.construct_interrupt_handler(ctx))
ui_element_request_mgr = SetUIElementRequestManager(set_ui_element_queue)
diff --git a/marimo/_runtime/context/kernel_context.py b/marimo/_runtime/context/kernel_context.py
index 8412269e11..eb0dba1f2b 100644
--- a/marimo/_runtime/context/kernel_context.py
+++ b/marimo/_runtime/context/kernel_context.py
@@ -36,6 +36,7 @@ class KernelRuntimeContext(RuntimeContext):
# app that owns this context; None for top-level contexts
_app: Optional[InternalApp] = None
_id_provider: Optional[IDProvider] = None
+ _execution_context: Optional[ExecutionContext] = None
@property
def graph(self) -> DirectedGraph:
@@ -47,7 +48,13 @@ class KernelRuntimeContext(RuntimeContext):
@property
def execution_context(self) -> ExecutionContext | None:
- return self._kernel.execution_context
+ return self._execution_context
+
+ @execution_context.setter
+ def execution_context(
+ self, execution_context: ExecutionContext | None
+ ) -> None:
+ self._execution_context = execution_context
@property
def marimo_config(self) -> MarimoConfig:
@@ -60,8 +67,8 @@ class KernelRuntimeContext(RuntimeContext):
@property
def cell_id(self) -> Optional[CellId_t]:
"""Get the cell id of the currently executing cell, if any."""
- if self._kernel.execution_context is not None:
- return self._kernel.execution_context.cell_id
+ if self.execution_context is not None:
+ return self.execution_context.cell_id
return None
@property
@@ -107,13 +114,13 @@ class KernelRuntimeContext(RuntimeContext):
setting_element_value = old.setting_element_value
else:
setting_element_value = False
- self._kernel.execution_context = ExecutionContext(
+ self.execution_context = ExecutionContext(
cell_id=cell_id,
setting_element_value=setting_element_value,
)
yield
finally:
- self._kernel.execution_context = old
+ self.execution_context = old
@property
def app(self) -> InternalApp:
@@ -163,18 +170,18 @@ def initialize_kernel_context(
stderr: Stderr | None,
virtual_files_supported: bool,
mode: SessionMode,
-) -> None:
+) -> KernelRuntimeContext:
"""Initializes thread-local/session-specific context.
Must be called exactly once for each client thread.
"""
- initialize_context(
- runtime_context=create_kernel_context(
- kernel=kernel,
- stream=stream,
- stdout=stdout,
- stderr=stderr,
- virtual_files_supported=virtual_files_supported,
- mode=mode,
- )
+ ctx = create_kernel_context(
+ kernel=kernel,
+ stream=stream,
+ stdout=stdout,
+ stderr=stderr,
+ virtual_files_supported=virtual_files_supported,
+ mode=mode,
)
+ initialize_context(runtime_context=ctx)
+ return ctx
diff --git a/marimo/_runtime/handlers.py b/marimo/_runtime/handlers.py
index 2a0de7b746..f8e29f7fa6 100644
--- a/marimo/_runtime/handlers.py
+++ b/marimo/_runtime/handlers.py
@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, Any, Callable
from marimo import _loggers
from marimo._messaging.ops import Interrupted
from marimo._runtime.context import get_context
+from marimo._runtime.context.kernel_context import KernelRuntimeContext
from marimo._runtime.control_flow import MarimoInterrupt
LOGGER = _loggers.marimo_logger()
@@ -15,7 +16,7 @@ if TYPE_CHECKING:
def construct_interrupt_handler(
- kernel: "Kernel",
+ context: KernelRuntimeContext,
) -> Callable[[int, Any], None]:
def interrupt_handler(signum: int, frame: Any) -> None:
"""Tries to interrupt the kernel."""
@@ -26,7 +27,7 @@ def construct_interrupt_handler(
# TODO(akshayka): if kernel is in `run` but not executing,
# it won't be interrupted, which isn't right ... but the
# probability of that happening is low.
- if kernel.execution_context is not None:
+ if context.execution_context is not None:
Interrupted().broadcast()
raise MarimoInterrupt
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index af722a2beb..255dc6d301 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -79,7 +79,10 @@ from marimo._runtime.context import (
ExecutionContext,
get_context,
)
-from marimo._runtime.context.kernel_context import initialize_kernel_context
+from marimo._runtime.context.kernel_context import (
+ KernelRuntimeContext,
+ initialize_kernel_context,
+)
from marimo._runtime.control_flow import MarimoInterrupt
from marimo._runtime.input_override import input_override
from marimo._runtime.packages.module_registry import ModuleRegistry
@@ -518,8 +521,6 @@ class Kernel:
).get("execution_type", "relaxed")
self._update_runtime_from_user_config(user_config)
- # Set up the execution context
- self.execution_context: Optional[ExecutionContext] = None
# initializers to override construction of ui elements
self.ui_initializers: dict[str, Any] = {}
# errored cells
@@ -648,8 +649,10 @@ class Kernel:
def _install_execution_context(
self, cell_id: CellId_t, setting_element_value: bool = False
) -> Iterator[ExecutionContext]:
- self.execution_context = ExecutionContext(
- cell_id, setting_element_value
+ ctx = get_context()
+ assert isinstance(ctx, KernelRuntimeContext)
+ ctx.execution_context = (
+ exec_ctx := ExecutionContext(cell_id, setting_element_value)
)
with (
get_context().provide_ui_ids(str(cell_id)),
@@ -669,9 +672,9 @@ class Kernel:
self.module_reloader.check(
modules=sys.modules, reload=True
)
- yield self.execution_context
+ yield exec_ctx
finally:
- self.execution_context = None
+ ctx.execution_context = None
if self.module_reloader is not None and modules is not None:
# Note timestamps for newly loaded modules
new_modules = set(sys.modules) - modules
@@ -1343,8 +1346,9 @@ class Kernel:
Should be called when a state's setter is called.
"""
# store the state and the currently executing cell
- assert self.execution_context is not None
- self.state_updates[state] = self.execution_context.cell_id
+ ctx = get_context()
+ assert ctx.execution_context is not None
+ self.state_updates[state] = ctx.execution_context.cell_id
# TODO(akshayka): Send VariableValues message for any globals
# bound to this state object (just like UI elements)
@@ -2200,7 +2204,7 @@ def launch_kernel(
user_config=user_config,
enqueue_control_request=_enqueue_control_request,
)
- initialize_kernel_context(
+ ctx = initialize_kernel_context(
kernel=kernel,
stream=stream,
stdout=stdout,
@@ -2228,9 +2232,7 @@ def launch_kernel(
# install the formatter import hooks
register_formatters(theme=user_config["display"]["theme"])
- signal.signal(
- signal.SIGINT, handlers.construct_interrupt_handler(kernel)
- )
+ signal.signal(signal.SIGINT, handlers.construct_interrupt_handler(ctx))
if sys.platform == "win32":
if interrupt_queue is not None:
diff --git a/marimo/_runtime/threads.py b/marimo/_runtime/threads.py
index 39c6a66f6e..c8492f92ac 100644
--- a/marimo/_runtime/threads.py
+++ b/marimo/_runtime/threads.py
@@ -4,7 +4,12 @@ from __future__ import annotations
import threading
from typing import Any
+from marimo._messaging.streams import ThreadSafeStream
+from marimo._pyodide.streams import PyodideStream
+from marimo._runtime.context.kernel_context import KernelRuntimeContext
+from marimo._runtime.context.script_context import ScriptRuntimeContext
from marimo._runtime.context.types import (
+ ExecutionContext,
RuntimeContext,
get_context,
initialize_context,
@@ -18,6 +23,10 @@ class Thread(threading.Thread):
`mo.Thread` has the same API as threading.Thread,
but `mo.Thread`s are able to communicate with the marimo
frontend, whereas `threading.Thread` can't.
+
+ Currently, threads can append to a cell's output using
+ `mo.output.append`, but messages written to stdout and stderr won't
+ be forwarded to the frontend.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
@@ -25,10 +34,54 @@ class Thread(threading.Thread):
self._marimo_ctx: RuntimeContext | None = None
- if runtime_context_installed():
- self._marimo_ctx = get_context()
+ if not runtime_context_installed():
+ return
+
+ ctx = get_context()
+ if isinstance(ctx, KernelRuntimeContext):
+ self._marimo_ctx = KernelRuntimeContext(**ctx.__dict__)
+ # standard IO is not yet threadsafe
+ self._marimo_ctx.stdout = None
+ self._marimo_ctx.stderr = None
+ if isinstance(ctx.stream, ThreadSafeStream):
+ self._marimo_ctx.stream = type(ctx.stream)(
+ pipe=ctx.stream.pipe,
+ # TODO(akshayka): stdin is not threadsafe
+ input_queue=ctx.stream.input_queue,
+ cell_id=ctx.stream.cell_id,
+ )
+ elif isinstance(ctx.stream, PyodideStream):
+ self._marimo_ctx.stream = type(ctx.stream)(
+ pipe=ctx.stream.pipe,
+ # TODO(akshayka): stdin is not threadsafe
+ input_queue=ctx.stream.input_queue,
+ cell_id=ctx.stream.cell_id,
+ )
+ else:
+ raise RuntimeError(
+ "Unsupported stream type " + str(type(ctx.stream))
+ )
+ elif isinstance(self._marimo_ctx, ScriptRuntimeContext):
+ # Standard streams are not rerouted when running as a script, so no
+ # need to set to None
+ self._marimo_ctx = ScriptRuntimeContext(**ctx.__dict__)
+ if isinstance(ctx.stream, ThreadSafeStream):
+ self._marimo_ctx.stream = ThreadSafeStream(
+ pipe=ctx.stream.pipe,
+ input_queue=ctx.stream.input_queue,
+ cell_id=ctx.stream.cell_id,
+ )
+ else:
+ raise RuntimeError(
+ "Unsupported stream type " + str(type(ctx.stream))
+ )
def run(self) -> None:
if self._marimo_ctx is not None:
initialize_context(self._marimo_ctx)
+ if isinstance(self._marimo_ctx, KernelRuntimeContext):
+ self._marimo_ctx.execution_context = ExecutionContext(
+ cell_id=self._marimo_ctx.stream.cell_id, # type: ignore
+ setting_element_value=False,
+ )
super().run()
diff --git a/tests/_runtime/test_threads.py b/tests/_runtime/test_threads.py
index b3cd4f3c94..8bc35afad2 100644
--- a/tests/_runtime/test_threads.py
+++ b/tests/_runtime/test_threads.py
@@ -4,15 +4,35 @@ from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
-async def test_set_ui_element_value_lensed(
- any_kernel: Kernel, exec_req: ExecReqProvider
-) -> None:
- """Test setting the value of a lensed element.
+# Doesn't work with strict kernel ...
+async def test_thread_set_global(k: Kernel, exec_req: ExecReqProvider) -> None:
+ """Test that a thread starts and runs."""
- Make sure reactivity flows through its parent, and that its on_change
- handler is called exactly once.
- """
- k = any_kernel
+ await k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get(
+ """
+ value = 0
+ def target():
+ global value
+ value = 1
+ """
+ ),
+ exec_req.get("t = mo.Thread(target=target); t.start(); t.join()"),
+ ]
+ )
+
+ # thread run should be basically instantaneous, but sleep just in case ...
+ assert not k.errors
+ time.sleep(0.01) # noqa: ASYNC251
+ assert k.globals["value"] == 1
+
+
+async def test_thread_has_own_stream(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ """Test that a thread starts and runs."""
await k.run(
[
@@ -20,16 +40,60 @@ async def test_set_ui_element_value_lensed(
exec_req.get("ctx_main = mo._runtime.context.get_context()"),
exec_req.get(
"""
- ctx_thread = None
+ cell_id = ctx_main.stream.cell_id
+ thread_ctx = None
+ def target():
+ global thread_ctx
+ thread_ctx = mo._runtime.context.get_context()
+ t = mo.Thread(target=target); t.start(); t.join()
+ """
+ ),
+ ]
+ )
+
+ # thread run should be basically instantaneous, but sleep just in case ...
+ assert not k.errors
+ time.sleep(0.01) # noqa: ASYNC251
+ # thread gets its own context
+ assert k.globals["thread_ctx"] != k.globals["ctx_main"]
+ stream = k.globals["thread_ctx"].stream
+ assert stream.cell_id == k.globals["cell_id"]
+
+
+async def test_thread_output_append(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ """Test that a thread starts and runs."""
+
+ await k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get(
+ """
+ stream = mo._runtime.context.get_context().stream
+ thread_stream = None
def target():
- global ctx_thread
- ctx_thread = mo._runtime.context.get_context()
- mo.Thread(target=target).start().join()
+ global thread_stream
+ import marimo as mo
+ mo.output.append("hello")
+ mo.output.append("world")
+ thread_stream = mo._runtime.context.get_context().stream
+ t = mo.Thread(target=target); t.start(); t.join()
"""
),
]
)
# thread run should be basically instantaneous, but sleep just in case ...
+ assert not k.errors
time.sleep(0.01) # noqa: ASYNC251
- assert k.globals["ctx_main"] == k.globals["ctx_thread"]
+ # The main thread should not have any output, but the new thread should
+ stream = k.globals["stream"]
+ for m in stream.messages:
+ if m[0] == "cell-op" and m[1]["output"] is not None:
+ assert "hello" not in m[1]["output"]["data"]
+ assert "world" not in m[1]["output"]["data"]
+ thread_stream = k.globals["thread_stream"]
+ assert len(thread_stream.messages) == 2
+ assert "hello" in thread_stream.messages[0][1]["output"]["data"]
+ assert "world" in thread_stream.messages[1][1]["output"]["data"]
diff --git a/tests/conftest.py b/tests/conftest.py
index 8d2bdfcb7c..84cf966af0 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -46,6 +46,10 @@ register_formatters()
class _MockStream(ThreadSafeStream):
"""Captures the ops sent through the stream"""
+ cell_id: int | None = None
+ input_queue: None = None
+ pipe: None = None
+
messages: list[tuple[str, dict[Any, Any]]] = dataclasses.field(
default_factory=list
)