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: enter and exit the kernel lifespan exactly once (#11370)
Dylan Madisetti2b550f198e55
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex fc6680b940..f58ecb0bdf 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -170,6 +170,7 @@ from marimo._sql.sql_quoting import (from marimo._tracer import attach_trace_context, kernel_tracerfrom marimo._types.ids import CellId_t, UIElementId, VariableNamefrom marimo._types.lifespan import Lifespan+from marimo._utils.asyncio_utils import run_coroutine_blockingfrom marimo._utils.lifespans import Lifespansfrom marimo._utils.paths import normalize_pathfrom marimo._utils.platform import is_pyodide@@ -672,6 +673,9 @@ class Kernel:)if lifespan.has_lifespans():self._lifespan = lifespan(None)+ # A kernel can be torn down without ever being instantiated, and+ # exiting a lifespan that was never entered raises.+ self._lifespan_entered = False@propertydef stream(self) -> Stream:@@ -716,9 +720,10 @@ class Kernel:# manually clear kernel memory.self._module.__dict__.clear()- # Teardown lifespans- if self._lifespan is not None:- asyncio.run(self._lifespan.__aexit__(None, None, None))+ # Teardown lifespans. NB. teardown can run inside an event loop,+ # where `asyncio.run` raises.+ if self._lifespan is not None and self._lifespan_entered:+ run_coroutine_blocking(self._lifespan.__aexit__(None, None, None))def lazy(self) -> bool:return self.reactive_execution_mode == "lazy"@@ -2368,8 +2373,11 @@ class Kernel:During instantiation, UIElements can check for an initial valuewith `get_initial_value`"""- if self._lifespan is not None:+ # A lifespan can only be entered once, but a kernel can be asked to+ # instantiate again.+ if self._lifespan is not None and not self._lifespan_entered:await self._lifespan.__aenter__()+ self._lifespan_entered = Trueself.load_dotenv()diff --git a/tests/_runtime/test_kernel_lifespan.py b/tests/_runtime/test_kernel_lifespan.pynew file mode 100644index 0000000000..13b8ccdd18--- /dev/null+++ b/tests/_runtime/test_kernel_lifespan.py@@ -0,0 +1,67 @@+# Copyright 2026 Marimo. All rights reserved.+"""Lifespans contributed through the `marimo.kernel.lifespan` registry."""++from __future__ import annotations++import contextlib+from typing import TYPE_CHECKING++import pytest++from marimo._runtime.commands import (+ CreateNotebookCommand,+ UpdateUIElementCommand,+)+from marimo._runtime.runtime import _KERNEL_LIFESPAN_REGISTRY+from tests._runtime._helpers.session import mocked_kernel_session++if TYPE_CHECKING:+ from collections.abc import AsyncIterator, Iterator+++def lifespan_events() -> Iterator[list[str]]:+ """Register a kernel lifespan that logs each enter and exit."""+ events: list[str] = []++ @contextlib.asynccontextmanager+ async def recorder(_app: None) -> AsyncIterator[None]:+ events.append("enter")+ try:+ yield+ finally:+ events.append("exit")++ _KERNEL_LIFESPAN_REGISTRY.register("recorder", recorder)+ try:+ yield events+ finally:+ _KERNEL_LIFESPAN_REGISTRY.unregister("recorder")+++def test_kernel_torn_down_before_instantiate_skips_lifespan(+ lifespan_events: list[str],+) -> None:+ with mocked_kernel_session():+ pass++ assert lifespan_events == []+++async def test_kernel_enters_and_exits_lifespan_once(+ lifespan_events: list[str],+) -> None:+ no_ui_values = UpdateUIElementCommand.from_ids_and_values([])+ request = CreateNotebookCommand(+ execution_requests=(),+ cell_ids=(),+ set_ui_element_value_request=no_ui_values,+ auto_run=True,+ )+ # The session exits inside this test's running event loop.+ with mocked_kernel_session() as tk:+ await tk.kernel.instantiate(request)+ await tk.kernel.instantiate(request)+ assert lifespan_events == ["enter"]++ assert lifespan_events == ["enter", "exit"]