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: per session app.embed() (#3694)

Akshay Agrawal4927cc781232
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index f524597833..d28f4e327b 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import ast
import base64
import inspect
+import threading
from dataclasses import asdict, dataclass, field
from pathlib import Path
from textwrap import dedent
@@ -37,6 +38,7 @@ from marimo._runtime import dataflow
from marimo._runtime.app.kernel_runner import AppKernelRunner
from marimo._runtime.app.script_runner import AppScriptRunner
from 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()
+
+
@mddoc
class 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 = True
def _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.py
index 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.py
index e291c144c0..428428b545 100644
--- a/marimo/_runtime/context/kernel_context.py
+++ b/marimo/_runtime/context/kernel_context.py
@@ -5,6 +5,7 @@ from contextlib import contextmanager
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Iterator, Optional
+from marimo._ast.app import AppKernelRunnerRegistry
from marimo._config.config import MarimoConfig
from marimo._messaging.types import Stderr, Stdout
from 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.py
index 521936efea..5794652356 100644
--- a/marimo/_runtime/context/script_context.py
+++ b/marimo/_runtime/context/script_context.py
@@ -6,6 +6,7 @@ from contextlib import contextmanager
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Iterator, Optional
+from marimo._ast.app import AppKernelRunnerRegistry
from marimo._cli.parse_args import args_from_argv
from marimo._config.config import MarimoConfig
from 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.py
index 217da534f5..8fd172772f 100644
--- a/marimo/_runtime/context/types.py
+++ b/marimo/_runtime/context/types.py
@@ -21,7 +21,7 @@ from marimo._runtime.functions import FunctionRegistry
from marimo._runtime.requests import HTTPRequest
if TYPE_CHECKING:
- from marimo._ast.app import InternalApp
+ from marimo._ast.app import AppKernelRunnerRegistry, InternalApp
from marimo._ast.cell import CellId_t
from marimo._messaging.types import Stream
from marimo._output.hypertext import Html
@@ -71,6 +71,7 @@ class RuntimeContext(abc.ABC):
cell_lifecycle_registry: CellLifecycleRegistry
virtual_file_registry: VirtualFileRegistry
virtual_files_supported: bool
+ app_kernel_runner_registry: AppKernelRunnerRegistry
# stream, stdout, stderr are _not_ owned by the context
stream: Stream
stdout: 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
@contextmanager
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 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.py
index 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 pathlib
import subprocess
import textwrap
-from typing import Any
+from typing import Any, TYPE_CHECKING
import pytest
-from marimo._ast.app import App, _AppConfig, InternalApp
+
+from marimo._ast.app import App, AppKernelRunnerRegistry, _AppConfig, InternalApp
from marimo._ast.errors import (
CycleError,
DeleteNonlocalError,
@@ -18,9 +18,11 @@ from marimo._ast.errors import (
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.stateless.flex import vstack
from marimo._runtime.requests import SetUIElementValueRequest
-from marimo._runtime.runtime import Kernel
from 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 == 2
assert 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