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
fix: per session app.embed() (#3694)
Akshay Agrawal4927cc781232
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex f524597833..d28f4e327b 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport astimport base64import inspect+import threadingfrom dataclasses import asdict, dataclass, fieldfrom pathlib import Pathfrom textwrap import dedent@@ -37,6 +38,7 @@ from marimo._runtime import dataflowfrom marimo._runtime.app.kernel_runner import AppKernelRunnerfrom marimo._runtime.app.script_runner import AppScriptRunnerfrom marimo._runtime.context.types import (+ ContextNotInitializedError,get_context,runtime_context_installed,)@@ -132,6 +134,31 @@ class AppEmbedResult:defs: Mapping[str, object]+class AppKernelRunnerRegistry:+ def __init__(self) -> None:+ # Mapping from thread to its kernel runners, so that app.embed() calls are+ # isolated across run sessions.+ self._runners: dict[int, dict[App, AppKernelRunner]] = {}++ def get_runner(self, app: App) -> AppKernelRunner:+ app_runners = self._runners.setdefault(threading.get_ident(), {})+ runner = app_runners.get(app, None)+ if runner is None:+ runner = AppKernelRunner(InternalApp(app))+ app_runners[app] = runner+ return runner++ def remove_runner(self, app: App) -> None:+ app_runners = self._runners.get(tid := threading.get_ident(), {})+ if app in app_runners:+ del app_runners[app]+ if tid in self._runners and not (self._runners[tid]):+ del self._runners[tid]++ def shutdown(self) -> None:+ self._runners.clear()++@mddocclass App:"""A marimo notebook.@@ -175,7 +202,12 @@ class App:self._filename = inspect.getfile(inspect.stack()[1].frame)except Exception:...- self._app_kernel_runner: AppKernelRunner | None = None++ def __del__(self) -> None:+ try:+ get_context().app_kernel_runner_registry.remove_runner(self)+ except ContextNotInitializedError:+ ...def clone(self) -> App:"""Clone an app to embed multiple copies of it.@@ -328,9 +360,7 @@ class App:self._initialized = Truedef _get_kernel_runner(self) -> AppKernelRunner:- if self._app_kernel_runner is None:- self._app_kernel_runner = AppKernelRunner(InternalApp(self))- return self._app_kernel_runner+ return get_context().app_kernel_runner_registry.get_runner(self)def _flatten_outputs(self, outputs: dict[CellId_t, Any]) -> Sequence[Any]:return tuple(diff --git a/marimo/_runtime/app/kernel_runner.py b/marimo/_runtime/app/kernel_runner.pyindex 0e05d89d9d..e840ccff75 100644--- a/marimo/_runtime/app/kernel_runner.py+++ b/marimo/_runtime/app/kernel_runner.py@@ -92,10 +92,9 @@ class AppKernelRunner:parent=ctx,)ctx.add_child(self._runtime_context)- finalizer = weakref.finalize(+ weakref.finalize(self, ctx.remove_child, self._runtime_context- )- finalizer.atexit = False+ ).atexit = False# Register cells through the kernel runner, so that compilation only# occurs once.diff --git a/marimo/_runtime/context/kernel_context.py b/marimo/_runtime/context/kernel_context.pyindex e291c144c0..428428b545 100644--- a/marimo/_runtime/context/kernel_context.py+++ b/marimo/_runtime/context/kernel_context.py@@ -5,6 +5,7 @@ from contextlib import contextmanagerfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Iterator, Optional+from marimo._ast.app import AppKernelRunnerRegistryfrom marimo._config.config import MarimoConfigfrom marimo._messaging.types import Stderr, Stdoutfrom marimo._plugins.ui._core.ids import IDProvider, NoIDProviderException@@ -152,6 +153,7 @@ def create_kernel_context(state_registry=StateRegistry(),function_registry=FunctionRegistry(),cell_lifecycle_registry=CellLifecycleRegistry(),+ app_kernel_runner_registry=AppKernelRunnerRegistry(),virtual_file_registry=VirtualFileRegistry(),virtual_files_supported=virtual_files_supported,stream=stream,diff --git a/marimo/_runtime/context/script_context.py b/marimo/_runtime/context/script_context.pyindex 521936efea..5794652356 100644--- a/marimo/_runtime/context/script_context.py+++ b/marimo/_runtime/context/script_context.py@@ -6,6 +6,7 @@ from contextlib import contextmanagerfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Iterator, Optional+from marimo._ast.app import AppKernelRunnerRegistryfrom marimo._cli.parse_args import args_from_argvfrom marimo._config.config import MarimoConfigfrom marimo._config.manager import get_default_config_manager@@ -140,6 +141,7 @@ def initialize_script_context(state_registry=StateRegistry(),function_registry=FunctionRegistry(),cell_lifecycle_registry=CellLifecycleRegistry(),+ app_kernel_runner_registry=AppKernelRunnerRegistry(),virtual_file_registry=VirtualFileRegistry(),virtual_files_supported=False,stream=stream,diff --git a/marimo/_runtime/context/types.py b/marimo/_runtime/context/types.pyindex 217da534f5..8fd172772f 100644--- a/marimo/_runtime/context/types.py+++ b/marimo/_runtime/context/types.py@@ -21,7 +21,7 @@ from marimo._runtime.functions import FunctionRegistryfrom marimo._runtime.requests import HTTPRequestif TYPE_CHECKING:- from marimo._ast.app import InternalApp+ from marimo._ast.app import AppKernelRunnerRegistry, InternalAppfrom marimo._ast.cell import CellId_tfrom marimo._messaging.types import Streamfrom marimo._output.hypertext import Html@@ -71,6 +71,7 @@ class RuntimeContext(abc.ABC):cell_lifecycle_registry: CellLifecycleRegistryvirtual_file_registry: VirtualFileRegistryvirtual_files_supported: bool+ app_kernel_runner_registry: AppKernelRunnerRegistry# stream, stdout, stderr are _not_ owned by the contextstream: Streamstdout: Stdout | None@@ -154,6 +155,7 @@ class RuntimeContext(abc.ABC):def remove_child(self, runtime_context: RuntimeContext) -> None:self.children.remove(runtime_context)+ runtime_context.virtual_file_registry.shutdown()assert runtime_context not in self.children@contextmanagerdiff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex d0e677f1a1..6b1668e9d0 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -2310,7 +2310,14 @@ def launch_kernel(profiler.disable()profiler.dump_stats(profile_path)+ # Defensively clear context data structures, in case a leak prevents+ # the context from being destroyed.+ #+ # TODO(akshayka): define ownership semantics for contexts, so the+ # context knows how to shut itself down. The virtual file registry+ # is shared between the main thread and mo.Thread's right now ...get_context().virtual_file_registry.shutdown()+ get_context().app_kernel_runner_registry.shutdown()teardown_context()kernel.teardown()if isinstance(pipe, connection.Connection):diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.pyindex e59de6ef4c..bf5add3c72 100644--- a/tests/_ast/test_app.py+++ b/tests/_ast/test_app.py@@ -1,14 +1,14 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-import pathlibimport subprocessimport textwrap-from typing import Any+from typing import Any, TYPE_CHECKINGimport pytest-from marimo._ast.app import App, _AppConfig, InternalApp++from marimo._ast.app import App, AppKernelRunnerRegistry, _AppConfig, InternalAppfrom marimo._ast.errors import (CycleError,DeleteNonlocalError,@@ -18,9 +18,11 @@ from marimo._ast.errors import (from marimo._dependencies.dependencies import DependencyManagerfrom marimo._plugins.stateless.flex import vstackfrom marimo._runtime.requests import SetUIElementValueRequest-from marimo._runtime.runtime import Kernelfrom tests.conftest import ExecReqProvider+if TYPE_CHECKING:+ from marimo._runtime.runtime import Kernel+# don't complain for useless expressions (cell outputs)# ruff: noqa: B018@@ -734,3 +736,20 @@ class TestAppComposition:assert x.value == 2assert y.value == 3+++class TestAppKernelRunnerRegistry:+ def test_get_runner(self, k: Kernel) -> None:+ # `k` fixture installs a context, needed for AppKernelRunner+ del k+ app = App()+ registry = AppKernelRunnerRegistry()+ # Calling with the same app yields the same runner+ assert registry.get_runner(app) == registry.get_runner(app)++ # Calling with different app objects yields different runners+ assert registry.get_runner(app) != registry.get_runner(other := App())++ registry.remove_runner(app)+ registry.remove_runner(other)+ assert not registry._runners