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: isolation when running multiple notebooks in an app server (#8611)

Akshay Agrawal1f0f376b4c42
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index 4c02585b19..791d280463 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -1189,6 +1189,14 @@ def run(
"pyzmq is required when running a gallery with --sandbox.",
"marimo[sandbox]",
)
+ elif is_multi:
+ from marimo._dependencies.dependencies import DependencyManager
+
+ if not DependencyManager.zmq.has():
+ raise MarimoCLIMissingDependencyError(
+ "pyzmq is required for running multiple notebooks.",
+ "pyzmq",
+ )
file_router = _create_run_file_router(validated_paths, watch=watch)
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index 641e28d68b..67ee2edd26 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -568,6 +568,7 @@ class ExperimentalConfig(TypedDict, total=False):
markdown: bool # Used in playground (community cloud)
wasm_layouts: bool # Used in playground (community cloud)
rtc_v2: bool
+ isolate_apps: bool
# Internal features
cache: CacheConfig
diff --git a/marimo/_ipc/connection.py b/marimo/_ipc/connection.py
index c8d9299d3b..1e5da6bce4 100644
--- a/marimo/_ipc/connection.py
+++ b/marimo/_ipc/connection.py
@@ -194,5 +194,7 @@ class Connection:
if self._receiver_thread.is_alive():
self._receiver_thread.join(timeout=1)
- # Close all associated sockets (and finally terminate)
- self.context.destroy()
+ # Close all sockets and terminate the context.
+ # linger=0 drops any unsent messages immediately, preventing
+ # hangs during shutdown when the remote end is already gone.
+ self.context.destroy(linger=0)
diff --git a/marimo/_server/asgi.py b/marimo/_server/asgi.py
index 1369493fd7..7d18df997a 100644
--- a/marimo/_server/asgi.py
+++ b/marimo/_server/asgi.py
@@ -462,6 +462,12 @@ def create_asgi_app(
else:
auth_token = AuthToken(token)
+ from marimo._dependencies.dependencies import DependencyManager
+
+ DependencyManager.zmq.require(
+ "for running multiple notebooks with create_asgi_app()"
+ )
+
# We call the entrypoint `root` instead of `filename` incase we want to
# support directories or code in the future
class Builder(ASGIAppBuilder):
@@ -521,6 +527,9 @@ def create_asgi_app(
auth_token=auth_token,
redirect_console_to_browser=redirect_console_to_browser,
ttl_seconds=session_ttl,
+ isolate_apps=config_reader.experimental.get(
+ "isolate_apps", False
+ ),
)
enable_auth = not AuthToken.is_empty(auth_token)
app = create_starlette_app(
diff --git a/marimo/_server/session_manager.py b/marimo/_server/session_manager.py
index a1c525fa61..6d576647ff 100644
--- a/marimo/_server/session_manager.py
+++ b/marimo/_server/session_manager.py
@@ -32,6 +32,7 @@ from marimo._server.resume_strategies import create_resume_strategy
from marimo._server.session.listeners import RecentsTrackerListener
from marimo._server.token_manager import TokenManager
from marimo._server.tokens import AuthToken, SkewProtectionToken
+from marimo._session.app_host import AppHostContext, AppHostPool
from marimo._session.consumer import SessionConsumer
from marimo._session.events import SessionEventBus
from marimo._session.extensions.types import SessionExtension
@@ -83,6 +84,7 @@ class SessionManager:
ttl_seconds: Optional[int],
watch: bool = False,
sandbox_mode: SandboxMode | None = None,
+ isolate_apps: bool = False,
) -> None:
# Core configuration
self.file_router = file_router
@@ -97,6 +99,15 @@ class SessionManager:
self._config_manager = config_manager
self.sandbox_mode = sandbox_mode
+ # When running multiple apps, each app runs in an isolated host
+ # process, to avoid collisions in sys.modules and other Python global
+ # structures. These processes are managed by an AppHostPool.
+ self._app_host_pool: AppHostPool | None = None
+ if isolate_apps and mode == SessionMode.RUN:
+ self._app_host_pool = AppHostPool(
+ sandbox=sandbox_mode is SandboxMode.MULTI,
+ )
+
self._repository = SessionRepository()
def _get_code() -> str:
@@ -222,6 +233,11 @@ class SessionManager:
auto_instantiate=auto_instantiate,
extensions=extensions,
sandbox_mode=self.sandbox_mode,
+ app_host_context=AppHostContext(
+ pool=self._app_host_pool, session_id=session_id
+ )
+ if self._app_host_pool
+ else None,
)
# Add to repository
@@ -393,6 +409,8 @@ class SessionManager:
"""Shutdown the session manager and stop all file watchers."""
LOGGER.debug("Shutting down")
self.close_all_sessions()
+ if self._app_host_pool is not None:
+ self._app_host_pool.shutdown()
self.lsp_server.stop()
self._watcher_manager.stop_all()
diff --git a/marimo/_server/start.py b/marimo/_server/start.py
index 1dc6723c71..541dca0052 100644
--- a/marimo/_server/start.py
+++ b/marimo/_server/start.py
@@ -248,6 +248,11 @@ def start(
}
)
+ is_multi = file_router.get_unique_file_key() is None
+ isolate_apps = is_multi and config_reader.experimental.get(
+ "isolate_apps", False
+ )
+
session_manager = SessionManager(
file_router=file_router,
mode=mode,
@@ -262,6 +267,7 @@ def start(
redirect_console_to_browser=redirect_console_to_browser,
watch=watch,
sandbox_mode=sandbox_mode,
+ isolate_apps=isolate_apps,
)
log_level = "info" if development_mode else "error"
diff --git a/marimo/_session/app_host/__init__.py b/marimo/_session/app_host/__init__.py
new file mode 100644
index 0000000000..f6fabf139b
--- /dev/null
+++ b/marimo/_session/app_host/__init__.py
@@ -0,0 +1,18 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""App isolation for serving multiple notebooks.
+
+Each notebook is hosted in an AppHost, which isolates the notebook from other
+running notebooks. Sessions for the same notebook are routed to a single
+AppHost.
+
+AppHosts are created and managed by an AppHostPool.
+"""
+
+from marimo._session.app_host.host import AppHost
+from marimo._session.app_host.pool import AppHostContext, AppHostPool
+
+__all__ = [
+ "AppHost",
+ "AppHostContext",
+ "AppHostPool",
+]
diff --git a/marimo/_session/app_host/commands.py b/marimo/_session/app_host/commands.py
new file mode 100644
index 0000000000..8421a633e3
--- /dev/null
+++ b/marimo/_session/app_host/commands.py
@@ -0,0 +1,116 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Commands and responses."""
+
+from __future__ import annotations
+
+import enum
+import typing
+
+import msgspec
+import msgspec.json
+
+from marimo._ast.cell import CellConfig
+from marimo._config.config import MarimoConfig
+from marimo._runtime.commands import AppMetadata
+from marimo._types.ids import CellId_t
+
+
+# ---------------- Management commands ---------------------
+class CreateKernelCmd(msgspec.Struct, tag=True):
+ """Request the app host to create a new kernel thread."""
+
+ session_id: str
+ configs: dict[CellId_t, CellConfig]
+ app_metadata: AppMetadata
+ user_config: MarimoConfig
+ virtual_files_supported: bool
+ redirect_console_to_browser: bool
+ log_level: int
+
+
+class StopKernelCmd(msgspec.Struct, tag=True):
+ """Request the app host to stop a kernel thread."""
+
+ session_id: str
+
+
+class ShutdownAppHostCmd(msgspec.Struct, tag=True):
+ """Request the app host to shut down entirely."""
+
+
+# ---------------- Management responses ---------------------
+class AppHostReadyResponse(msgspec.Struct, tag=True):
+ """Signals that the app host has started and is ready."""
+
+
+class KernelCreatedResponse(msgspec.Struct, tag=True):
+ """Confirms a kernel was created (or reports failure)."""
+
+ session_id: str
+ success: bool
+ error: str | None = None
+
+
+# ---------------- Management encoders and decoders ---------------------
+MgmtCommand = typing.Union[CreateKernelCmd, StopKernelCmd, ShutdownAppHostCmd]
+MgmtResponse = typing.Union[AppHostReadyResponse, KernelCreatedResponse]
+
+_cmd_decoder = msgspec.json.Decoder(MgmtCommand)
+_resp_decoder = msgspec.json.Decoder(MgmtResponse)
+
+
+def encode_mgmt_command(cmd: MgmtCommand) -> bytes:
+ return msgspec.json.encode(cmd)
+
+
+def decode_mgmt_command(data: bytes) -> MgmtCommand:
+ result: MgmtCommand = _cmd_decoder.decode(data)
+ return result
+
+
+def encode_mgmt_response(resp: MgmtResponse) -> bytes:
+ return msgspec.json.encode(resp)
+
+
+def decode_mgmt_response(data: bytes) -> MgmtResponse:
+ result: MgmtResponse = _resp_decoder.decode(data)
+ return result
+
+
+# ---------------- AppHost initialization ----------------
+class AppHostArgs(msgspec.Struct):
+ """Args sent to the AppHost process."""
+
+ # ZMQ PULL address for receiving management commands
+ mgmt_addr: str
+ # ZMQ PUSH address for sending management responses
+ response_addr: str
+ # ZMQ PULL address for receiving kernel commands
+ cmd_addr: str
+ # ZMQ PUSH address for sending kernel output
+ stream_addr: str
+ # Notebook file path, for debug logs
+ file_path: str
+ log_level: int
+
+ def encode_json(self) -> bytes:
+ return msgspec.json.encode(self)
+
+ @classmethod
+ def decode_json(cls, buf: bytes) -> AppHostArgs:
+ return msgspec.json.decode(buf, type=cls)
+
+
+# ---------------- Kernel ----------------
+class Channel(enum.Enum):
+ """Command channels."""
+
+ CONTROL = b"control"
+ UI_ELEMENT = b"ui_element"
+ COMPLETION = b"completion"
+ INPUT = b"input"
+
+
+# Sentinel sent on the stream channel when a kernel thread exits.
+class KernelExited:
+ """Signals that a kernel thread has exited."""
diff --git a/marimo/_session/app_host/connection.py b/marimo/_session/app_host/connection.py
new file mode 100644
index 0000000000..599900fde2
--- /dev/null
+++ b/marimo/_session/app_host/connection.py
@@ -0,0 +1,87 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""ZMQ connection management for IPC between an app host and its process."""
+
+from __future__ import annotations
+
+import dataclasses
+from typing import TYPE_CHECKING
+
+from marimo._config.settings import GLOBAL_SETTINGS
+from marimo._session.app_host.commands import AppHostArgs
+
+if TYPE_CHECKING:
+ import zmq
+
+_BIND_ADDR = "tcp://127.0.0.1"
+
+
+class AppHostConnection:
+ """Manages all ZeroMQ sockets for an AppHost."""
+
+ context: zmq.Context[zmq.Socket[bytes]]
+
+ # PUSH — single frame: encode_mgmt_command(MgmtCommand)
+ mgmt: zmq.Socket[bytes]
+ # PULL — single frame: decode_mgmt_response(bytes) -> MgmtResponse
+ response: zmq.Socket[bytes]
+
+ # TODO(akshayka): Consider moving to something less fragile than pickle
+ # PUSH — 3-frame multipart: [session_id, channel, pickle(payload)]
+ cmd: zmq.Socket[bytes]
+ # PULL — 2-frame multipart: [session_id, pickle(KernelMessage | KernelExited)]
+ stream: zmq.Socket[bytes]
+
+ @classmethod
+ def create(
+ cls, file_path: str, log_level: int | None = None
+ ) -> tuple[AppHostConnection, AppHostArgs]:
+ """Bind all sockets, return connection and args for subprocess."""
+ import zmq
+
+ if log_level is None:
+ log_level = GLOBAL_SETTINGS.LOG_LEVEL
+
+ context = zmq.Context()
+ try:
+ mgmt = context.socket(zmq.PUSH)
+ mgmt_port = mgmt.bind_to_random_port(_BIND_ADDR)
+
+ response = context.socket(zmq.PULL)
+ response_port = response.bind_to_random_port(_BIND_ADDR)
+
+ cmd = context.socket(zmq.PUSH)
+ cmd_port = cmd.bind_to_random_port(_BIND_ADDR)
+
+ stream = context.socket(zmq.PULL)
+ stream_port = stream.bind_to_random_port(_BIND_ADDR)
+ except Exception:
+ context.destroy(linger=0)
+ raise
+
+ conn = cls(
+ context=context,
+ mgmt=mgmt,
+ response=response,
+ cmd=cmd,
+ stream=stream,
+ )
+
+ args = AppHostArgs(
+ mgmt_addr=f"{_BIND_ADDR}:{mgmt_port}",
+ response_addr=f"{_BIND_ADDR}:{response_port}",
+ cmd_addr=f"{_BIND_ADDR}:{cmd_port}",
+ stream_addr=f"{_BIND_ADDR}:{stream_port}",
+ file_path=file_path,
+ log_level=log_level,
+ )
+
+ return conn, args
+
+ def close(self) -> None:
+ """Close all sockets and destroy context."""
+ self.mgmt.close(linger=0)
+ self.response.close(linger=0)
+ self.cmd.close(linger=0)
+ self.stream.close(linger=0)
+ self.context.destroy(linger=0)
diff --git a/marimo/_session/app_host/host.py b/marimo/_session/app_host/host.py
new file mode 100644
index 0000000000..3829c82435
--- /dev/null
+++ b/marimo/_session/app_host/host.py
@@ -0,0 +1,381 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""A container for a single notebook supporting multiple client sessions."""
+
+from __future__ import annotations
+
+import pickle
+import subprocess
+import sys
+import threading
+from typing import TYPE_CHECKING
+
+from marimo import _loggers
+from marimo._messaging.types import KernelMessage
+from marimo._session.app_host.commands import (
+ AppHostReadyResponse,
+ Channel,
+ CreateKernelCmd,
+ KernelCreatedResponse,
+ KernelExited,
+ ShutdownAppHostCmd,
+ StopKernelCmd,
+ decode_mgmt_response,
+ encode_mgmt_command,
+)
+from marimo._session.app_host.connection import AppHostConnection
+
+if TYPE_CHECKING:
+ import queue
+ from collections.abc import Callable
+
+ from marimo._ast.cell import CellConfig
+ from marimo._config.config import MarimoConfig
+ from marimo._runtime.commands import AppMetadata
+ from marimo._types.ids import CellId_t
+
+LOGGER = _loggers.marimo_logger()
+
+
+class AppHost:
+ """Encapsulates an app with multiple client sessions.
+
+ The AppHost runs client kernels for a single app in a separate process,
+ coordinating communication between the server and client sessions and
+ multiplexing by session ID.
+
+ Args:
+ file_path: the notebook's absolute path, for debugging
+ python: absolute path to the Python executable
+ sandbox_dir: where to store the temporary venv if the notebook is sandboxed
+ on_empty: callable invoked when the AppHost spins down to zero sessions
+ """
+
+ def __init__(
+ self,
+ file_path: str,
+ python: str | None = None,
+ sandbox_dir: str | None = None,
+ on_empty: Callable[[], None] | None = None,
+ ) -> None:
+ self._file_path = file_path
+ self._python = python or sys.executable
+ self._sandbox_dir = sandbox_dir
+ self._on_empty = on_empty
+
+ # The process hosting client kernels.
+ self._process: subprocess.Popen[bytes] | None = None
+ self._conn: AppHostConnection | None = None
+
+ # Set by shutdown(); checked by the stream receiver loop and
+ # by send helpers to avoid operating on closed sockets.
+ self._closed = threading.Event()
+
+ # A map from each client session to a unique queue for its kernel's outputs
+ # This map is protected by a lock, because a receiver thread drains its
+ # outputs.
+ self._stream_lock = threading.Lock()
+ self._stream_receivers: dict[
+ str, queue.Queue[KernelMessage | None]
+ ] = {}
+
+ # Serializes mgmt send and response recv so concurrent create_kernel
+ # calls don't interleave on the shared ZMQ sockets.
+ self._mgmt_lock = threading.Lock()
+
+ # Session IDs are accessed on kernel creation but also on
+ # session removal.
+ self._session_lock = threading.Lock()
+ self._session_ids: set[str] = set()
+
+ def _fire_on_empty(self) -> bool:
+ """If no sessions remain, fire _on_empty on a background thread."""
+ callback = None
+ with self._session_lock:
+ if not self._session_ids:
+ callback = self._on_empty
+ self._on_empty = None
+ if callback is not None:
+ LOGGER.debug(
+ "AppHost for %s has no active sessions, invoking cleanup",
+ self._file_path,
+ )
+ # Run on a separate thread; calling shutdown directly
+ # would close the ZMQ socket the caller may be reading.
+ threading.Thread(target=callback, daemon=True).start()
+ return True
+ return False
+
+ def _stream_receiver_loop(self) -> None:
+ """Read stream messages from the app host and route to sessions."""
+ import zmq
+
+ conn = self._conn
+ assert conn is not None # start() sets _conn before this thread
+
+ while not self._closed.is_set():
+ try:
+ # Poll with a timeout so we periodically re-check
+ # _closed. A blocking recv_multipart() would prevent
+ # context.destroy() from completing.
+ if not conn.stream.poll(timeout=1000):
+ # If the subprocess died, no more KernelExited
+ # sentinels will arrive. Fire _on_empty so the
+ # pool can clean up this AppHost.
+ if not self.is_alive():
+ with self._session_lock:
+ self._session_ids.clear()
+ self._fire_on_empty()
+ break
+ continue
+
+ frames = conn.stream.recv_multipart()
+ session_id = frames[0].decode()
+ payload = pickle.loads(frames[1])
+
+ if isinstance(payload, KernelExited):
+ with self._session_lock:
+ self._session_ids.discard(session_id)
+ LOGGER.debug(
+ "Kernel thread exited for session %s",
+ session_id,
+ )
+ if self._fire_on_empty():
+ break
+ continue
+
+ with self._stream_lock:
+ q = self._stream_receivers.get(session_id)
+
+ if q is not None:
+ q.put(payload)
+ else:
+ LOGGER.debug(
+ "Dropping stream message for unknown session %s",
+ session_id,
+ )
+ except zmq.ZMQError:
+ break
+ except Exception:
+ LOGGER.warning("Error in stream receiver", exc_info=True)
+
+ def start(self) -> None:
+ conn, args = AppHostConnection.create(self._file_path)
+ self._conn = conn
+
+ cmd = [
+ self._python,
+ "-m",
+ "marimo._session.app_host.main",
+ ]
+ LOGGER.debug("Launching app host: %s", " ".join(cmd))
+
+ # stdin is piped to send startup args; stdout/stderr inherit the
+ # parent's file descriptors to make sure we don't interfere
+ # with kernels' console outputs.
+ self._process = subprocess.Popen(
+ cmd,
+ stdin=subprocess.PIPE,
+ )
+
+ proc_stdin = self._process.stdin
+ if proc_stdin is None:
+ self.shutdown()
+ raise RuntimeError("Failed to open stdin for app host")
+
+ ready_timeout_ms = 30_000
+ try:
+ proc_stdin.write(args.encode_json())
+ proc_stdin.flush()
+ proc_stdin.close()
+ if not conn.response.poll(timeout=ready_timeout_ms):
+ raise RuntimeError(
+ f"App host timed out ({ready_timeout_ms // 1000}s) "
+ f"for {self._file_path}"
+ )
+
+ data = conn.response.recv()
+ ready_response = decode_mgmt_response(data)
+ if not isinstance(ready_response, AppHostReadyResponse):
+ raise RuntimeError(
+ f"Unexpected response during startup: "
+ f"{type(ready_response)}"
+ )
+ except Exception:
+ self.shutdown()
+ raise
+
+ stream_thread = threading.Thread(
+ target=self._stream_receiver_loop, daemon=True
+ )
+ stream_thread.start()
+
+ LOGGER.debug(
+ "App host started for %s (pid=%s)",
+ self._file_path,
+ self._process.pid,
+ )
+
+ def send_command(
+ self, session_id: str, channel: Channel, payload: object
+ ) -> None:
+ """Send a command to a kernel in the app host."""
+ conn = self._conn
+ if conn is None or self._closed.is_set():
+ return
+ try:
+ conn.cmd.send_multipart(
+ [
+ session_id.encode(),
+ channel.value,
+ pickle.dumps(payload),
+ ]
+ )
+ except Exception:
+ pass
+
+ def register_stream(
+ self, session_id: str, q: queue.Queue[KernelMessage | None]
+ ) -> None:
+ """Register a stream queue to receive output for a session."""
+ with self._stream_lock:
+ self._stream_receivers[session_id] = q
+
+ def unregister_stream(self, session_id: str) -> None:
+ """Unregister a session's stream queue."""
+ with self._stream_lock:
+ self._stream_receivers.pop(session_id, None)
+
+ def create_kernel(
+ self,
+ session_id: str,
+ configs: dict[CellId_t, CellConfig],
+ app_metadata: AppMetadata,
+ user_config: MarimoConfig,
+ virtual_files_supported: bool,
+ redirect_console_to_browser: bool,
+ log_level: int,
+ ) -> KernelCreatedResponse:
+ conn = self._conn
+ if conn is None or self._closed.is_set():
+ raise RuntimeError("App host not started")
+
+ cmd = CreateKernelCmd(
+ session_id=session_id,
+ configs=configs,
+ app_metadata=app_metadata,
+ user_config=user_config,
+ virtual_files_supported=virtual_files_supported,
+ redirect_console_to_browser=redirect_console_to_browser,
+ log_level=log_level,
+ )
+
+ # Pre-register so _on_empty won't fire while we wait for the
+ # response. Also prevents a KernelExited that arrives before
+ # the response from leaving a zombie entry (the discard will
+ # find the id in the set).
+ with self._session_lock:
+ self._session_ids.add(session_id)
+
+ # Serialize send+recv so concurrent create_kernel calls don't
+ # interleave on the shared mgmt/response ZMQ sockets.
+ try:
+ with self._mgmt_lock:
+ conn.mgmt.send(encode_mgmt_command(cmd))
+
+ response_timeout_ms = 30_000
+ if conn.response.poll(timeout=response_timeout_ms):
+ data = conn.response.recv()
+ response = decode_mgmt_response(data)
+ if not isinstance(response, KernelCreatedResponse):
+ raise RuntimeError(
+ f"Unexpected response type: {type(response)}"
+ )
+ if not response.success:
+ with self._session_lock:
+ self._session_ids.discard(session_id)
+ return response
+ raise TimeoutError(
+ f"Timed out waiting for kernel creation "
+ f"in {self._file_path}"
+ )
+ except Exception:
+ with self._session_lock:
+ self._session_ids.discard(session_id)
+ raise
+
+ def stop_kernel(self, session_id: str) -> None:
+ conn = self._conn
+ if conn is None or self._closed.is_set():
+ return
+ try:
+ conn.mgmt.send(
+ encode_mgmt_command(StopKernelCmd(session_id=session_id))
+ )
+ except Exception:
+ pass
+
+ def has_active_session(self, session_id: str) -> bool:
+ """Check if a specific kernel thread is alive in this host."""
+ with self._session_lock:
+ has_session = session_id in self._session_ids
+ return (
+ has_session
+ and self._process is not None
+ and self._process.poll() is None
+ )
+
+ def is_alive(self) -> bool:
+ return self._process is not None and self._process.poll() is None
+
+ @property
+ def pid(self) -> int | None:
+ return self._process.pid if self._process else None
+
+ def shutdown(self) -> None:
+ import zmq
+
+ if self._closed.is_set():
+ return
+ self._closed.set()
+
+ # Signal all registered stream receivers to stop, so their
+ # QueueDistributor threads don't hang waiting for messages.
+ with self._stream_lock:
+ for q in self._stream_receivers.values():
+ try:
+ q.put(None)
+ except Exception:
+ pass
+ self._stream_receivers.clear()
+
+ conn = self._conn
+ if conn is not None:
+ try:
+ conn.mgmt.send(encode_mgmt_command(ShutdownAppHostCmd()))
+ except zmq.ZMQError:
+ pass
+
+ if self._process is not None:
+ try:
+ self._process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ self._process.terminate()
+ try:
+ self._process.wait(timeout=2)
+ except subprocess.TimeoutExpired:
+ self._process.kill()
+
+ # Close all sockets (with linger=0). This interrupts any
+ # pending poll()/recv() in _stream_receiver_loop with ETERM,
+ # causing it to exit cleanly. send_command/stop_kernel/
+ # create_kernel check _closed before touching sockets.
+ if conn is not None:
+ conn.close()
+
+ if self._sandbox_dir is not None:
+ from marimo._cli.sandbox import cleanup_sandbox_dir
+
+ cleanup_sandbox_dir(self._sandbox_dir)
+ self._sandbox_dir = None
+
+ LOGGER.debug("App host shut down for %s", self._file_path)
diff --git a/marimo/_session/app_host/main.py b/marimo/_session/app_host/main.py
new file mode 100644
index 0000000000..c69541f8f2
--- /dev/null
+++ b/marimo/_session/app_host/main.py
@@ -0,0 +1,344 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""The entry point for the app host process, which serves multiple clients.
+
+Each app host manages kernel threads for a single notebook file (one thread per
+client session).
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import os
+import pickle
+import queue
+import signal
+import sys
+import threading
+import typing
+
+from marimo import _loggers
+from marimo._messaging.thread_local_streams import install_thread_local_proxies
+from marimo._output.formatters.formatters import register_formatters
+from marimo._runtime import runtime
+from marimo._runtime.commands import StopKernelCommand
+from marimo._session.app_host.commands import (
+ AppHostArgs,
+ AppHostReadyResponse,
+ Channel,
+ CreateKernelCmd,
+ KernelCreatedResponse,
+ KernelExited,
+ ShutdownAppHostCmd,
+ StopKernelCmd,
+ decode_mgmt_command,
+ encode_mgmt_response,
+)
+
+LOGGER = _loggers.marimo_logger()
+
+
+class _KernelQueues:
+ control: queue.Queue[typing.Any]
+ ui_element: queue.Queue[typing.Any]
+ completion: queue.Queue[typing.Any]
+ input: queue.Queue[typing.Any]
+
+
+class _KernelInfo:
+ thread: threading.Thread
+ queues: _KernelQueues
+ session_id: str
+
+
+class _TaggedStreamQueue:
+ """Queue that tags messages with session_id and puts in shared outbox.
+
+ Passed to launch_kernel as stream_queue. The kernel calls put() to send
+ output; messages are tagged with session_id and forwarded to the shared
+ outbox queue, which a collector thread reads and sends over ZMQ.
+ """
+
+ def __init__(
+ self, session_id: str, outbox: queue.Queue[typing.Any]
+ ) -> None:
+ self._session_id = session_id
+ self._outbox = outbox
+
+ def put(
+ self,
+ item: object,
+ /,
+ block: bool = True,
+ timeout: float | None = None,
+ ) -> None:
+ self._outbox.put(
+ (self._session_id, item), block=block, timeout=timeout
+ )
+
+ def put_nowait(self, item: object, /) -> None:
+ self._outbox.put_nowait((self._session_id, item))
+
+ def get(
+ self, block: bool = True, timeout: float | None = None
+ ) -> typing.Any:
+ raise NotImplementedError("TaggedStreamQueue is write-only")
+
+ def get_nowait(self) -> typing.Any:
+ raise NotImplementedError("TaggedStreamQueue is write-only")
+
+ def empty(self) -> bool:
+ return True
+
+
+def _handle_command(
+ cmd_socket: typing.Any,
+ kernels: dict[str, _KernelInfo],
+) -> None:
+ """Read one multiplexed command from ZMQ and route to the kernel queue."""
+ frames = cmd_socket.recv_multipart()
+ session_id = frames[0].decode()
+ channel = Channel(frames[1])
+ payload = pickle.loads(frames[2])
+
+ info = kernels.get(session_id)
+ if info is None:
+ LOGGER.debug("Dropping command for unknown session %s", session_id)
+ return
+
+ if channel is Channel.CONTROL:
+ info.queues.control.put(payload)
+ elif channel is Channel.UI_ELEMENT:
+ info.queues.ui_element.put(payload)
+ elif channel is Channel.COMPLETION:
+ info.queues.completion.put(payload)
+ elif channel is Channel.INPUT:
+ info.queues.input.put(payload)
+
+
+def _stream_collector_loop(
+ stream_outbox: queue.Queue[typing.Any],
+ stream_socket: typing.Any,
+) -> None:
+ """Read tagged stream messages from outbox and send over ZMQ."""
+ while True:
+ item = stream_outbox.get()
+ if item is None:
+ break
+ session_id, msg = item
+ try:
+ stream_socket.send_multipart(
+ [session_id.encode(), pickle.dumps(msg)]
+ )
+ except Exception:
+ LOGGER.exception(
+ "Error sending stream message for session %s", session_id
+ )
+
+
+def _shutdown_all_kernels(
+ kernels: dict[str, _KernelInfo],
+) -> None:
+ for info in kernels.values():
+ try:
+ info.queues.control.put(StopKernelCommand())
+ except Exception:
+ LOGGER.exception(
+ "Error stopping kernel for session %s", info.session_id
+ )
+ kernels.clear()
+
+
+def _handle_stop_kernel(
+ cmd: StopKernelCmd,
+ kernels: dict[str, _KernelInfo],
+) -> None:
+ info = kernels.pop(cmd.session_id, None)
+ if info is not None:
+ info.queues.control.put(StopKernelCommand())
+ LOGGER.debug("Kernel stopped for session %s", cmd.session_id)
+
+
+def _handle_create_kernel(
+ cmd: CreateKernelCmd,
+ kernels: dict[str, _KernelInfo],
+ stream_outbox: queue.Queue[typing.Any],
+ response_socket: typing.Any,
+) -> None:
+ try:
+ command_queues = _KernelQueues(
+ control=queue.Queue(),
+ ui_element=queue.Queue(),
+ completion=queue.Queue(),
+ input=queue.Queue(maxsize=1),
+ )
+ stream_queue = _TaggedStreamQueue(cmd.session_id, stream_outbox)
+
+ def launch_kernel_with_cleanup() -> None:
+ try:
+ runtime.launch_kernel(
+ control_queue=command_queues.control,
+ set_ui_element_queue=command_queues.ui_element,
+ completion_queue=command_queues.completion,
+ input_queue=command_queues.input,
+ stream_queue=stream_queue,
+ socket_addr=None,
+ is_edit_mode=False,
+ configs=cmd.configs,
+ app_metadata=cmd.app_metadata,
+ user_config=cmd.user_config,
+ virtual_files_supported=cmd.virtual_files_supported,
+ redirect_console_to_browser=cmd.redirect_console_to_browser,
+ interrupt_queue=None,
+ log_level=cmd.log_level,
+ is_ipc=False,
+ )
+ except Exception:
+ LOGGER.exception(
+ "Kernel thread crashed for session %s", cmd.session_id
+ )
+ finally:
+ stream_queue.put(KernelExited())
+
+ thread = threading.Thread(
+ target=launch_kernel_with_cleanup,
+ daemon=True,
+ )
+ thread.start()
+
+ kernels[cmd.session_id] = _KernelInfo(
+ thread=thread,
+ queues=command_queues,
+ session_id=cmd.session_id,
+ )
+
+ response_socket.send(
+ encode_mgmt_response(
+ KernelCreatedResponse(session_id=cmd.session_id, success=True)
+ )
+ )
+ LOGGER.debug("Kernel created for session %s", cmd.session_id)
+
+ except Exception as e:
+ LOGGER.exception(
+ "Failed to create kernel for session %s", cmd.session_id
+ )
+ response_socket.send(
+ encode_mgmt_response(
+ KernelCreatedResponse(
+ session_id=cmd.session_id, success=False, error=str(e)
+ )
+ )
+ )
+
+
+def app_host_main(args: AppHostArgs) -> None:
+ """App host main loop.
+
+ Connects to the management ZMQ sockets and data channels, then processes
+ management commands to create/stop kernel threads. Kernel commands and
+ stream output flow through multiplexed data channels, not per-kernel
+ ZMQ connections.
+ """
+ import zmq
+
+ # Ignore SIGINT in app host processes. The main process handles Ctrl-C
+ # and sends ShutdownAppHostCmd via the management channel.
+ signal.signal(signal.SIGINT, signal.SIG_IGN)
+
+ _loggers.set_level(args.log_level)
+ LOGGER.debug(
+ "App host started for %s (pid=%d)", args.file_path, os.getpid()
+ )
+
+ # Register formatters once, shared by all kernel threads in this app host.
+ register_formatters()
+
+ # Install thread-local stream proxies once at process startup, shared by
+ # all kernel threads (not per-kernel).
+ install_thread_local_proxies()
+
+ context = zmq.Context()
+
+ # Management channel
+ mgmt_socket = context.socket(zmq.PULL)
+ mgmt_socket.connect(args.mgmt_addr)
+ response_socket = context.socket(zmq.PUSH)
+ response_socket.connect(args.response_addr)
+
+ # Multiplexed command and output channels
+ cmd_socket = context.socket(zmq.PULL)
+ cmd_socket.connect(args.cmd_addr)
+ stream_socket = context.socket(zmq.PUSH)
+ stream_socket.connect(args.stream_addr)
+
+ # A separate thread collects outputs from kernels and forwards them to the
+ # AppHost that started this process.
+ stream_outbox: queue.Queue[typing.Any] = queue.Queue()
+ collector_thread = threading.Thread(
+ target=_stream_collector_loop,
+ args=(stream_outbox, stream_socket),
+ daemon=True,
+ )
+ collector_thread.start()
+ response_socket.send(encode_mgmt_response(AppHostReadyResponse()))
+
+ kernels: dict[str, _KernelInfo] = {}
+ poller = zmq.Poller()
+ poller.register(mgmt_socket, zmq.POLLIN)
+ poller.register(cmd_socket, zmq.POLLIN)
+ while True:
+ events = dict(poller.poll())
+
+ if cmd_socket in events:
+ _handle_command(cmd_socket, kernels)
+
+ if mgmt_socket in events:
+ data = mgmt_socket.recv()
+ cmd = decode_mgmt_command(data)
+
+ if isinstance(cmd, CreateKernelCmd):
+ _handle_create_kernel(
+ cmd, kernels, stream_outbox, response_socket
+ )
+ elif isinstance(cmd, StopKernelCmd):
+ _handle_stop_kernel(cmd, kernels)
+ elif isinstance(cmd, ShutdownAppHostCmd):
+ LOGGER.debug("App host shutting down for %s", args.file_path)
+ _shutdown_all_kernels(kernels)
+ stream_outbox.put(None) # Stop collector thread
+ break
+ else:
+ LOGGER.warning(
+ "App host received unknown command: %s", type(cmd)
+ )
+
+ mgmt_socket.close(linger=0)
+ response_socket.close(linger=0)
+ cmd_socket.close(linger=0)
+ stream_socket.close(linger=0)
+ context.destroy(linger=0)
+
+
+def main() -> None:
+ # Read startup args with a timeout. If the parent process crashes before
+ # closing stdin, read() would block forever.
+ result: list[bytes] = []
+ reader = threading.Thread(
+ target=lambda: result.append(sys.stdin.buffer.read()),
+ daemon=True,
+ )
+ reader.start()
+ reader.join(timeout=30)
+ if not result:
+ sys.stderr.write(
+ "Timed out reading startup args from parent process\n"
+ )
+ sys.exit(1)
+ args = AppHostArgs.decode_json(result[0])
+ app_host_main(args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/marimo/_session/app_host/pool.py b/marimo/_session/app_host/pool.py
new file mode 100644
index 0000000000..2972b47205
--- /dev/null
+++ b/marimo/_session/app_host/pool.py
@@ -0,0 +1,130 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Provides AppHosts for notebooks.
+
+Each app is run in its own AppHost, providing isolation.
+"""
+
+from __future__ import annotations
+
+import os
+import threading
+from dataclasses import dataclass
+
+from marimo import _loggers
+from marimo._cli.sandbox import build_sandbox_venv, cleanup_sandbox_dir
+from marimo._session._venv import get_ipc_kernel_deps
+from marimo._session.app_host.host import AppHost
+
+LOGGER = _loggers.marimo_logger()
+
+
+class AppHostPool:
+ def __init__(self, sandbox: bool = False) -> None:
+ self._workers: dict[str, AppHost] = {}
+ self._lock = threading.Lock()
+ self._sandbox = sandbox
+
+ def _remove_and_shutdown(self, abs_path: str) -> None:
+ """Remove an app host from the pool and shut it down.
+
+ Called when the host has zero active kernels.
+ """
+ with self._lock:
+ worker = self._workers.pop(abs_path, None)
+
+ if worker is not None:
+ LOGGER.debug(
+ "Shutting down app host for %s (no active kernels)",
+ abs_path,
+ )
+ worker.shutdown()
+
+ def get_or_create(self, file_path: str) -> AppHost:
+ abs_path = os.path.abspath(file_path)
+
+ if self._sandbox:
+ return self._get_or_create_sandboxed(abs_path)
+
+ with self._lock:
+ return self._create_locked(abs_path)
+
+ def _get_or_create_sandboxed(self, abs_path: str) -> AppHost:
+ """Get or create an AppHost with a sandboxed venv.
+
+ Uses double-check locking: the venv build (which can take many
+ seconds) runs outside the lock to avoid blocking other threads.
+ """
+ with self._lock:
+ worker = self._workers.get(abs_path)
+ if worker is not None and worker.is_alive():
+ return worker
+
+ # Build sandbox venv outside lock (can take many seconds)
+ sandbox_dir, python = build_sandbox_venv(
+ abs_path, additional_deps=get_ipc_kernel_deps()
+ )
+
+ with self._lock:
+ # Re-check. Another thread may have created it while we were
+ # building the venv
+ worker = self._workers.get(abs_path)
+ if worker is not None and worker.is_alive():
+ cleanup_sandbox_dir(sandbox_dir)
+ return worker
+
+ return self._create_locked(
+ abs_path, python=python, sandbox_dir=sandbox_dir
+ )
+
+ def _create_locked(
+ self,
+ abs_path: str,
+ python: str | None = None,
+ sandbox_dir: str | None = None,
+ ) -> AppHost:
+ """Create a new AppHost, replacing a dead one if present.
+
+ Must be called while holding self._lock.
+ """
+ worker = self._workers.get(abs_path)
+ if worker is not None and worker.is_alive():
+ return worker
+
+ if worker is not None:
+ LOGGER.warning("App host for %s was dead, respawning", abs_path)
+ worker.shutdown()
+
+ def _on_empty() -> None:
+ self._remove_and_shutdown(abs_path)
+
+ worker = AppHost(
+ abs_path,
+ python=python,
+ sandbox_dir=sandbox_dir,
+ on_empty=_on_empty,
+ )
+ worker.start()
+ self._workers[abs_path] = worker
+ return worker
+
+ def shutdown(self) -> None:
+ # Collect and clear under the lock, then shut down outside
+ # it. worker.shutdown() can trigger _on_empty callbacks that
+ # call _remove_and_shutdown, which also acquires self._lock;
+ # Holding the lock here would deadlock.
+ with self._lock:
+ workers = list(self._workers.values())
+ self._workers.clear()
+
+ for worker in workers:
+ worker.shutdown()
+
+
+@dataclass(frozen=True)
+class AppHostContext:
+ """Everything a session needs to create its kernel inside an AppHost."""
+
+ # The pool that provides the app host for a notebook
+ pool: AppHostPool
+ # The session ID corresponding to the kernel to create
+ session_id: str
diff --git a/marimo/_session/managers/app_host.py b/marimo/_session/managers/app_host.py
new file mode 100644
index 0000000000..fb6b0df396
--- /dev/null
+++ b/marimo/_session/managers/app_host.py
@@ -0,0 +1,222 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""QueueManager and KernelManager adapters for an AppHost.
+
+These adapt AppHost's multiplexed ZMQ channels to the session manager
+protocols (QueueManager, KernelManager).
+"""
+
+from __future__ import annotations
+
+import queue
+from typing import TYPE_CHECKING, TypeVar
+
+from marimo._config.settings import GLOBAL_SETTINGS
+from marimo._messaging.types import KernelMessage
+from marimo._runtime import commands
+from marimo._session.app_host.commands import Channel
+from marimo._session.model import SessionMode
+from marimo._session.queue import ProcessLike, QueueType, route_control_request
+from marimo._session.types import (
+ KernelManager,
+ QueueManager as QueueManagerProto,
+)
+
+if TYPE_CHECKING:
+ import threading
+
+ from marimo._ast.cell import CellConfig
+ from marimo._config.manager import MarimoConfigReader
+ from marimo._runtime.commands import AppMetadata
+ from marimo._session.app_host.host import AppHost
+ from marimo._types.ids import CellId_t
+ from marimo._utils.typed_connection import TypedConnection
+
+_T = TypeVar("_T")
+
+
+class _AppHostPushQueue(QueueType[_T]):
+ """Queue that sends commands over the multiplexed ZMQ channel.
+
+ Satisfies QueueType protocol for the main-process side. Only put()
+ is meaningful; get() raises NotImplementedError since this queue
+ is write-only from the main process perspective.
+ """
+
+ def __init__(
+ self, app_host: AppHost, session_id: str, channel: Channel
+ ) -> None:
+ self._app_host = app_host
+ self._session_id = session_id
+ self._channel = channel
+
+ def put(
+ self,
+ item: _T,
+ /,
+ block: bool = True,
+ timeout: float | None = None,
+ ) -> None:
+ del block, timeout
+ self._app_host.send_command(self._session_id, self._channel, item)
+
+ def put_nowait(self, item: _T, /) -> None:
+ self.put(item)
+
+ def get(self, block: bool = True, timeout: float | None = None) -> _T:
+ raise NotImplementedError("_AppHostPushQueue is write-only")
+
+ def get_nowait(self) -> _T:
+ raise NotImplementedError("_AppHostPushQueue is write-only")
+
+ def empty(self) -> bool:
+ return True
+
+
+class AppHostQueueManager(QueueManagerProto):
+ """QueueManager for multiplexed app host communication.
+
+ Commands are sent over a shared ZMQ channel (tagged with session_id
+ and channel type). Stream output arrives via a per-session queue
+ filled by the AppHost stream receiver thread.
+ """
+
+ def __init__(self, app_host: AppHost, session_id: str) -> None:
+ self._app_host = app_host
+ self._session_id = session_id
+
+ self.control_queue: QueueType[commands.CommandMessage] = (
+ _AppHostPushQueue(app_host, session_id, Channel.CONTROL)
+ )
+ self.set_ui_element_queue: QueueType[commands.BatchableCommand] = (
+ _AppHostPushQueue(app_host, session_id, Channel.UI_ELEMENT)
+ )
+ self.completion_queue: QueueType[commands.CodeCompletionCommand] = (
+ _AppHostPushQueue(app_host, session_id, Channel.COMPLETION)
+ )
+ self.input_queue: QueueType[str] = _AppHostPushQueue(
+ app_host, session_id, Channel.INPUT
+ )
+ self.win32_interrupt_queue: None = None
+
+ self.stream_queue: queue.Queue[KernelMessage | None] = queue.Queue()
+ app_host.register_stream(session_id, self.stream_queue)
+
+ def put_control_request(self, request: commands.CommandMessage) -> None:
+ route_control_request(
+ request,
+ self.control_queue,
+ self.completion_queue,
+ self.set_ui_element_queue,
+ )
+
+ def put_input(self, text: str) -> None:
+ self.input_queue.put(text)
+
+ def close_queues(self) -> None:
+ self._app_host.unregister_stream(self._session_id)
+ self.stream_queue.put(None) # Signal QueueDistributor to stop
+
+
+class _AppHostLike(ProcessLike):
+ """Makes AppHost satisfy ProcessLike for kernel_task."""
+
+ def __init__(self, app_host: AppHost, session_id: str) -> None:
+ self._app_host = app_host
+ self._session_id = session_id
+
+ @property
+ def pid(self) -> int | None:
+ return self._app_host.pid
+
+ def is_alive(self) -> bool:
+ return self._app_host.has_active_session(self._session_id)
+
+ def terminate(self) -> None:
+ # We can't forcibly terminate a kernel thread
+ pass
+
+ def join(self, timeout: float | None = None) -> None:
+ # We never join kernel threads, just let them get cleaned up
+ # on their own
+ pass
+
+
+class AppHostKernelManager(KernelManager):
+ """Manages the kernel for a single client session inside an app host.
+
+ Each kernel (client session) is served by a thread inside an app's
+ host process.
+
+ Has a reference to an AppHost object which starts kernel threads
+ and coordinates communication from the server to kernel threads
+ and back.
+ """
+
+ def __init__(
+ self,
+ *,
+ app_host: AppHost,
+ session_id: str,
+ queue_manager: QueueManagerProto,
+ mode: SessionMode,
+ configs: dict[CellId_t, CellConfig],
+ app_metadata: AppMetadata,
+ config_manager: MarimoConfigReader,
+ redirect_console_to_browser: bool,
+ ) -> None:
+ self._app_host = app_host
+ self._session_id = session_id
+ self.queue_manager = queue_manager
+ self.mode = mode
+ self._configs = configs
+ self._app_metadata = app_metadata
+ self._config_manager = config_manager
+ self._redirect_console_to_browser = redirect_console_to_browser
+
+ self.kernel_task: ProcessLike | threading.Thread | None = None
+
+ def start_kernel(self) -> None:
+ response = self._app_host.create_kernel(
+ session_id=self._session_id,
+ configs=self._configs,
+ app_metadata=self._app_metadata,
+ user_config=self._config_manager.get_config(hide_secrets=False),
+ virtual_files_supported=True,
+ redirect_console_to_browser=self._redirect_console_to_browser,
+ log_level=GLOBAL_SETTINGS.LOG_LEVEL,
+ )
+
+ if not response.success:
+ raise RuntimeError(
+ f"Failed to create kernel in app host: {response.error}"
+ )
+
+ # The kernel thread is created in a separate process so we don't
+ # have access to its underlying thread.
+ self.kernel_task = _AppHostLike(self._app_host, self._session_id)
+
+ @property
+ def pid(self) -> int | None:
+ return self._app_host.pid
+
+ @property
+ def profile_path(self) -> str | None:
+ return None
+
+ def is_alive(self) -> bool:
+ return self._app_host.has_active_session(self._session_id)
+
+ def interrupt_kernel(self) -> None:
+ # Run-mode threads can't be interrupted
+ pass
+
+ def close_kernel(self) -> None:
+ self.queue_manager.close_queues()
+ self._app_host.stop_kernel(self._session_id)
+
+ @property
+ def kernel_connection(self) -> TypedConnection[KernelMessage]:
+ # App host kernels use stream_queue, not kernel_connection
+ raise NotImplementedError(
+ "App host kernel uses stream_queue, not kernel_connection"
+ )
diff --git a/marimo/_session/managers/ipc.py b/marimo/_session/managers/ipc.py
index 3af4e93232..a0c22ae942 100644
--- a/marimo/_session/managers/ipc.py
+++ b/marimo/_session/managers/ipc.py
@@ -33,7 +33,7 @@ from marimo._session._venv import (
install_marimo_into_venv,
)
from marimo._session.model import SessionMode
-from marimo._session.queue import ProcessLike, QueueType
+from marimo._session.queue import ProcessLike, QueueType, route_control_request
from marimo._session.types import KernelManager, QueueManager
from marimo._utils.typed_connection import TypedConnection
@@ -115,15 +115,12 @@ class IPCQueueManagerImpl(QueueManager):
self._ipc.close_queues()
def put_control_request(self, request: commands.CommandMessage) -> None:
- # Completions are on their own queue
- if isinstance(request, commands.CodeCompletionCommand):
- self.completion_queue.put(request)
- return
-
- self.control_queue.put(request)
- # Update UI elements are on both queues so they can be batched
- if isinstance(request, commands.UpdateUIElementCommand):
- self.set_ui_element_queue.put(request)
+ route_control_request(
+ request,
+ self.control_queue,
+ self.completion_queue,
+ self.set_ui_element_queue,
+ )
def put_input(self, text: str) -> None:
self.input_queue.put(text)
diff --git a/marimo/_session/managers/queue.py b/marimo/_session/managers/queue.py
index dd7f9e2abe..24182b3e2b 100644
--- a/marimo/_session/managers/queue.py
+++ b/marimo/_session/managers/queue.py
@@ -11,6 +11,7 @@ from typing import Optional, Union
from marimo._messaging.types import KernelMessage
from marimo._runtime import commands
+from marimo._session.queue import route_control_request
from marimo._session.types import QueueManager
@@ -95,19 +96,12 @@ class QueueManagerImpl(QueueManager):
def put_control_request(self, request: commands.CommandMessage) -> None:
"""Put a control request in the control queue."""
- # Completions are on their own queue
- if isinstance(request, commands.CodeCompletionCommand):
- self.completion_queue.put(request)
- return
-
- self.control_queue.put(request)
- # UI element updates and model commands are on both queues
- # so they can be batched
- if isinstance(
+ route_control_request(
request,
- (commands.UpdateUIElementCommand, commands.ModelCommand),
- ):
- self.set_ui_element_queue.put(request)
+ self.control_queue,
+ self.completion_queue,
+ self.set_ui_element_queue,
+ )
def put_input(self, text: str) -> None:
"""Put an input request in the input queue."""
diff --git a/marimo/_session/queue.py b/marimo/_session/queue.py
index d10d30aa7d..ffe3e48ea2 100644
--- a/marimo/_session/queue.py
+++ b/marimo/_session/queue.py
@@ -1,7 +1,10 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Optional, Protocol, TypeVar, Union
+from typing import TYPE_CHECKING, Optional, Protocol, TypeVar, Union
+
+if TYPE_CHECKING:
+ from marimo._runtime import commands
T = TypeVar("T")
@@ -30,6 +33,32 @@ class QueueType(Protocol[T]):
def empty(self) -> bool: ...
+def route_control_request(
+ request: commands.CommandMessage,
+ control_queue: QueueType[commands.CommandMessage],
+ completion_queue: QueueType[commands.CodeCompletionCommand],
+ ui_element_queue: QueueType[commands.BatchableCommand],
+) -> None:
+ """Route a control request to the appropriate queue(s).
+
+ - CodeCompletionCommand → completion_queue only
+ - UpdateUIElementCommand / ModelCommand → control_queue + ui_element_queue
+ - Everything else → control_queue only
+ """
+ from marimo._runtime import commands
+
+ if isinstance(request, commands.CodeCompletionCommand):
+ completion_queue.put(request)
+ return
+
+ control_queue.put(request)
+ if isinstance(
+ request,
+ (commands.UpdateUIElementCommand, commands.ModelCommand),
+ ):
+ ui_element_queue.put(request)
+
+
class ProcessLike(Protocol):
"""Protocol for process-like objects."""
diff --git a/marimo/_session/session.py b/marimo/_session/session.py
index d203d12378..42d3b2dfe1 100644
--- a/marimo/_session/session.py
+++ b/marimo/_session/session.py
@@ -62,6 +62,7 @@ if TYPE_CHECKING:
from collections.abc import Iterator, Mapping
from marimo._server.models.models import InstantiateNotebookRequest
+ from marimo._session.app_host import AppHostContext
LOGGER = _loggers.marimo_logger()
@@ -93,6 +94,7 @@ class SessionImpl(Session):
ttl_seconds: Optional[int],
extensions: list[SessionExtension] | None = None,
sandbox_mode: SandboxMode | None = None,
+ app_host_context: AppHostContext | None = None,
) -> Session:
"""
Create a new session.
@@ -106,10 +108,38 @@ class SessionImpl(Session):
configs = app_file_manager.app.cell_manager.config_map()
# Create kernel manager
- # SandboxMode.MULTI uses IPC kernels with per-notebook sandboxed venvs
+ # AppHost path handles multi-app run mode (both sandbox and non-sandbox).
+ # SandboxMode.MULTI falls through to IPC kernels only in edit mode.
queue_manager: QueueManager
kernel_manager: KernelManager
- if sandbox_mode is SandboxMode.MULTI:
+ if app_host_context is not None and mode == SessionMode.RUN:
+ from marimo._session.managers.app_host import (
+ AppHostKernelManager,
+ AppHostQueueManager,
+ )
+
+ file_path = app_file_manager.path
+ if file_path is None:
+ raise ValueError(
+ "App host isolation requires a file-backed notebook"
+ )
+ app_host = app_host_context.pool.get_or_create(file_path)
+ queue_manager = AppHostQueueManager(
+ app_host, app_host_context.session_id
+ )
+ kernel_manager = AppHostKernelManager(
+ app_host=app_host,
+ session_id=app_host_context.session_id,
+ queue_manager=queue_manager,
+ mode=mode,
+ configs=configs,
+ app_metadata=app_metadata,
+ config_manager=config_manager,
+ redirect_console_to_browser=redirect_console_to_browser,
+ )
+ elif sandbox_mode is SandboxMode.MULTI:
+ # IPC kernel path — edit mode with sandbox
+ # (AppHostPool is never created in edit mode)
from marimo._ipc import QueueManager as IPCQueueManager
from marimo._session.managers import (
IPCKernelManagerImpl,
diff --git a/marimo/_smoke_tests/process_isolation/README.md b/marimo/_smoke_tests/process_isolation/README.md
new file mode 100644
index 0000000000..34e7421145
--- /dev/null
+++ b/marimo/_smoke_tests/process_isolation/README.md
@@ -0,0 +1,48 @@
+# Process Isolation Smoke Test
+
+Tests that multiple notebooks served together get separate OS processes,
+preventing `sys.modules` clashes.
+
+## The Problem
+
+When two notebooks both `import shared_module` but expect different
+implementations (from different directories on `sys.path`), a shared
+process means whichever loads first wins.
+
+## Test Structure
+
+```
+process_isolation/
+├── app1.py # Notebook: sys.path += app1_modules, import shared_module
+├── app2.py # Notebook: sys.path += app2_modules, import shared_module
+├── app1_modules/
+│ └── shared_module.py # APP_NAME="app1", MAGIC_NUMBER=111
+├── app2_modules/
+│ └── shared_module.py # APP_NAME="app2", MAGIC_NUMBER=222
+├── serve.py # Serves both apps via create_asgi_app()
+└── README.md
+```
+
+## How to Run
+
+```bash
+# Option A: create_asgi_app()
+python marimo/_smoke_tests/process_isolation/serve.py
+
+# Option B: marimo run (multi-file, auto-enables process isolation)
+marimo run marimo/_smoke_tests/process_isolation/app1.py \
+ marimo/_smoke_tests/process_isolation/app2.py
+
+# Option C: marimo run --sandbox (multi-file, sandbox + process isolation)
+marimo run --sandbox marimo/_smoke_tests/process_isolation/app1.py \
+ marimo/_smoke_tests/process_isolation/app2.py
+```
+
+Open both apps in browser. Each should show a green "PASS" callout.
+
+## Expected Results
+
+- **With app/process isolation**: Both apps show PASS for process isolation.
+- **With `--sandbox`**: Both apps additionally show a green "Sandbox: PASS" callout —
+ each app's unique dependency (`humanize` for app1, `pyfiglet` for app2) was installed
+ in its own sandbox venv, and the other app's dependency is not present.
diff --git a/marimo/_smoke_tests/process_isolation/app1.py b/marimo/_smoke_tests/process_isolation/app1.py
new file mode 100644
index 0000000000..d05f839a6e
--- /dev/null
+++ b/marimo/_smoke_tests/process_isolation/app1.py
@@ -0,0 +1,166 @@
+# /// script
+# requires-python = ">=3.13"
+# dependencies = [
+# "marimo",
+# "humanize",
+# ]
+# ///
+import marimo
+
+__generated_with = "0.13.0"
+app = marimo.App()
+
+
+def _():
+ import sys
+ from pathlib import Path
+
+ # Add our own modules directory to sys.path so `import shared_module`
+ # resolves to OUR version of the module.
+ _modules_dir = str(Path(__file__).parent / "app1_modules")
+ if _modules_dir not in sys.path:
+ sys.path.insert(0, _modules_dir)
+
+ # Both app1 and app2 do `import shared_module` — same top-level name,
+ # different directories. Without process isolation, whichever loads
+ # first wins (the other gets the wrong module from sys.modules cache).
+ import shared_module # noqa: E402
+
+ identity = shared_module.get_identity()
+ return (identity, shared_module)
+
+
+def _(identity, shared_module):
+ import os
+ import threading
+
+ import marimo as mo
+
+ pid = os.getpid()
+ tid = threading.get_ident()
+
+ expected_app = "app1"
+ expected_magic = 111
+
+ is_correct = (
+ identity["app"] == expected_app and identity["magic"] == expected_magic
+ )
+
+ if is_correct:
+ status = mo.md(
+ f"""
+ ## App 1 — Process Isolation: PASS
+
+ | Field | Value | Expected |
+ |-------|-------|----------|
+ | `APP_NAME` | `{identity['app']}` | `{expected_app}` |
+ | `MAGIC_NUMBER` | `{identity['magic']}` | `{expected_magic}` |
+ | `__file__` | `{shared_module.__file__}` | — |
+ | `PID` | `{pid}` | — |
+ | `Thread ID` | `{tid}` | — |
+ """
+ ).callout(kind="success")
+ else:
+ status = mo.md(
+ f"""
+ ## App 1 — Process Isolation: FAIL
+
+ | Field | Value | Expected |
+ |-------|-------|----------|
+ | `APP_NAME` | `{identity['app']}` | `{expected_app}` |
+ | `MAGIC_NUMBER` | `{identity['magic']}` | `{expected_magic}` |
+ | `__file__` | `{shared_module.__file__}` | — |
+ | `PID` | `{pid}` | — |
+ | `Thread ID` | `{tid}` | — |
+
+ **Module clash!** Got another app's `shared_module`.
+ """
+ ).callout(kind="danger")
+
+ print("HELLO FROM APP 1")
+
+ status
+ return
+
+
+def _():
+ in_sandbox = sys.prefix != sys.base_prefix
+
+ # Try importing the sandbox-only dep for this app
+ sandbox_dep_ok = False
+ try:
+ import humanize
+
+ sandbox_dep_ok = True
+ dep_info = f"`humanize` {humanize.__version__}"
+ except ImportError:
+ dep_info = "`humanize` not installed"
+
+ # Check that the OTHER app's sandbox dep is NOT available
+ other_dep_leaked = False
+ try:
+ import pyfiglet # noqa: F401
+
+ other_dep_leaked = True
+ except ImportError:
+ pass
+
+ if in_sandbox:
+ if sandbox_dep_ok and not other_dep_leaked:
+ sandbox_status = mo.md(
+ f"""
+ ## App 1 — Sandbox: PASS
+
+ | Field | Value |
+ |-------|-------|
+ | `sys.executable` | `{sys.executable}` |
+ | `sys.prefix` | `{sys.prefix}` |
+ | Sandbox dep | {dep_info} |
+ | Other app's dep leaked? | No |
+ """
+ ).callout(kind="success")
+ else:
+ sandbox_status = mo.md(
+ f"""
+ ## App 1 — Sandbox: FAIL
+
+ | Field | Value |
+ |-------|-------|
+ | `sys.executable` | `{sys.executable}` |
+ | `sys.prefix` | `{sys.prefix}` |
+ | Sandbox dep | {dep_info} |
+ | Other app's dep leaked? | {"Yes" if other_dep_leaked else "No"} |
+ """
+ ).callout(kind="danger")
+ else:
+ sandbox_status = mo.md(
+ f"""
+ ## App 1 — Not running in sandbox mode
+
+ `sys.executable`: `{sys.executable}`
+
+ Run with `--sandbox` to test sandbox isolation.
+ """
+ ).callout(kind="warn")
+
+ sandbox_status
+ return
+
+
+def _(mo):
+ slider = mo.ui.slider(1, 20)
+ slider
+ return slider,
+
+
+def _(slider):
+ slider.value
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/process_isolation/app1_modules/shared_module.py b/marimo/_smoke_tests/process_isolation/app1_modules/shared_module.py
new file mode 100644
index 0000000000..18c7af91ee
--- /dev/null
+++ b/marimo/_smoke_tests/process_isolation/app1_modules/shared_module.py
@@ -0,0 +1,13 @@
+"""This module is imported by app1.py as 'shared_module'.
+
+Both app1 and app2 import a module named 'shared_module' but from different
+directories. Without process isolation, whichever loads first wins.
+With process isolation, each app gets its own copy.
+"""
+
+APP_NAME = "app1"
+MAGIC_NUMBER = 111
+
+
+def get_identity():
+ return {"app": APP_NAME, "magic": MAGIC_NUMBER}
diff --git a/marimo/_smoke_tests/process_isolation/app2.py b/marimo/_smoke_tests/process_isolation/app2.py
new file mode 100644
index 0000000000..d11b64ea5b
--- /dev/null
+++ b/marimo/_smoke_tests/process_isolation/app2.py
@@ -0,0 +1,153 @@
+# /// script
+# requires-python = ">=3.13"
+# dependencies = [
+# "marimo",
+# "pyfiglet",
+# ]
+# ///
+import marimo
+
+__generated_with = "0.13.0"
+app = marimo.App()
+
+
+def _():
+ import sys
+ from pathlib import Path
+
+ # Add our own modules directory to sys.path so `import shared_module`
+ # resolves to OUR version of the module.
+ _modules_dir = str(Path(__file__).parent / "app2_modules")
+ if _modules_dir not in sys.path:
+ sys.path.insert(0, _modules_dir)
+
+ # Both app1 and app2 do `import shared_module` — same top-level name,
+ # different directories. Without process isolation, whichever loads
+ # first wins (the other gets the wrong module from sys.modules cache).
+ import shared_module # noqa: E402
+
+ identity = shared_module.get_identity()
+ return (identity, shared_module)
+
+
+def _(identity, shared_module):
+ import os
+ import threading
+
+ import marimo as mo
+
+ pid = os.getpid()
+ tid = threading.get_ident()
+
+ expected_app = "app2"
+ expected_magic = 222
+
+ is_correct = (
+ identity["app"] == expected_app and identity["magic"] == expected_magic
+ )
+
+ if is_correct:
+ status = mo.md(
+ f"""
+ ## App 2 — Process Isolation: PASS
+
+ | Field | Value | Expected |
+ |-------|-------|----------|
+ | `APP_NAME` | `{identity['app']}` | `{expected_app}` |
+ | `MAGIC_NUMBER` | `{identity['magic']}` | `{expected_magic}` |
+ | `__file__` | `{shared_module.__file__}` | — |
+ | `PID` | `{pid}` | — |
+ | `Thread ID` | `{tid}` | — |
+ """
+ ).callout(kind="success")
+ else:
+ status = mo.md(
+ f"""
+ ## App 2 — Process Isolation: FAIL
+
+ | Field | Value | Expected |
+ |-------|-------|----------|
+ | `APP_NAME` | `{identity['app']}` | `{expected_app}` |
+ | `MAGIC_NUMBER` | `{identity['magic']}` | `{expected_magic}` |
+ | `__file__` | `{shared_module.__file__}` | — |
+ | `PID` | `{pid}` | — |
+ | `Thread ID` | `{tid}` | — |
+
+ **Module clash!** Got another app's `shared_module`.
+ """
+ ).callout(kind="danger")
+
+ status
+ return
+
+
+def _():
+ # Detect sandbox mode by checking if we're in a venv
+ in_sandbox = sys.prefix != sys.base_prefix
+
+ # Try importing the sandbox-only dep for this app
+ sandbox_dep_ok = False
+ try:
+ import pyfiglet
+
+ sandbox_dep_ok = True
+ dep_info = f"`pyfiglet` {pyfiglet.__version__}"
+ except ImportError:
+ dep_info = "`pyfiglet` not installed"
+
+ # Check that the OTHER app's sandbox dep is NOT available
+ other_dep_leaked = False
+ try:
+ import humanize # noqa: F401
+
+ other_dep_leaked = True
+ except ImportError:
+ pass
+
+ if in_sandbox:
+ if sandbox_dep_ok and not other_dep_leaked:
+ sandbox_status = mo.md(
+ f"""
+ ## App 2 — Sandbox: PASS
+
+ | Field | Value |
+ |-------|-------|
+ | `sys.executable` | `{sys.executable}` |
+ | `sys.prefix` | `{sys.prefix}` |
+ | Sandbox dep | {dep_info} |
+ | Other app's dep leaked? | No |
+ """
+ ).callout(kind="success")
+ else:
+ sandbox_status = mo.md(
+ f"""
+ ## App 2 — Sandbox: FAIL
+
+ | Field | Value |
+ |-------|-------|
+ | `sys.executable` | `{sys.executable}` |
+ | `sys.prefix` | `{sys.prefix}` |
+ | Sandbox dep | {dep_info} |
+ | Other app's dep leaked? | {"Yes" if other_dep_leaked else "No"} |
+ """
+ ).callout(kind="danger")
+ else:
+ sandbox_status = mo.md(
+ f"""
+ ## App 2 — Not running in sandbox mode
+
+ `sys.executable`: `{sys.executable}`
+
+ Run with `--sandbox` to test sandbox isolation.
+ """
+ ).callout(kind="warn")
+
+ sandbox_status
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/process_isolation/app2_modules/shared_module.py b/marimo/_smoke_tests/process_isolation/app2_modules/shared_module.py
new file mode 100644
index 0000000000..1f72481b63
--- /dev/null
+++ b/marimo/_smoke_tests/process_isolation/app2_modules/shared_module.py
@@ -0,0 +1,13 @@
+"""This module is imported by app2.py as 'shared_module'.
+
+Both app1 and app2 import a module named 'shared_module' but from different
+directories. Without process isolation, whichever loads first wins.
+With process isolation, each app gets its own copy.
+"""
+
+APP_NAME = "app2"
+MAGIC_NUMBER = 222
+
+
+def get_identity():
+ return {"app": APP_NAME, "magic": MAGIC_NUMBER}
diff --git a/marimo/_smoke_tests/process_isolation/serve.py b/marimo/_smoke_tests/process_isolation/serve.py
new file mode 100644
index 0000000000..0fccacfa5e
--- /dev/null
+++ b/marimo/_smoke_tests/process_isolation/serve.py
@@ -0,0 +1,54 @@
+# /// script
+# requires-python = ">=3.12"
+# dependencies = [
+# "marimo",
+# "pyzmq",
+# "starlette",
+# "uvicorn",
+# ]
+# [tool.uv.sources]
+# marimo = {path = "../../..", editable = true}
+# ///
+
+"""Smoke test for per-app worker process isolation.
+
+This script serves two notebooks (app1.py and app2.py) that each import a
+module named `shared_module` — but from different directories with different
+contents. Without process isolation, whichever app loads `shared_module`
+first would win, and the other app would get the wrong module. With process
+isolation, each app runs in its own OS process, so `sys.modules` is not shared.
+
+Usage (pick one):
+
+ # Option 1: create_asgi_app() — always uses process isolation
+ python marimo/_smoke_tests/process_isolation/serve.py
+
+ # Option 2: marimo run with multiple files — auto-enables process isolation
+ marimo run marimo/_smoke_tests/process_isolation/app1.py \
+ marimo/_smoke_tests/process_isolation/app2.py
+
+Then open:
+ - http://localhost:8000/app1/ — should show "PASS" with APP_NAME=app1
+ - http://localhost:8000/app2/ — should show "PASS" with APP_NAME=app2
+
+If both show PASS, process isolation is working correctly.
+If either shows FAIL, the module clash bug is present.
+"""
+
+from pathlib import Path
+
+import marimo
+import uvicorn
+
+here = Path(__file__).parent
+
+app = (
+ marimo.create_asgi_app()
+ .with_app(path="/app1", root=str(here / "app1.py"))
+ .with_app(path="/app2", root=str(here / "app2.py"))
+ .build()
+)
+
+if __name__ == "__main__":
+ print(__doc__)
+ uvicorn.run(app, host="localhost", port=8000, log_level="info")
diff --git a/pyproject.toml b/pyproject.toml
index d003550fd1..8c5d94020d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -50,6 +50,8 @@ dependencies = [
# for packaging.version; not sure what the lower bound is.
"packaging",
"msgspec>=0.20.0",
+ # for IPC, required for marimo edit --sandbox, marimo run <multiple notebooks>
+ "pyzmq>=27.1.0; python_version < '3.15'",
]
readme = "README.md"
license = { file = "LICENSE" }
@@ -436,7 +438,9 @@ banned-module-level-imports = [
"typing_extensions",
"pyiceberg",
"redshift_connector",
- "pydantic_ai"
+ "pydantic_ai",
+ # a top-level import of zmq may break WASM
+ "zmq"
]
[tool.ruff.lint.flake8-pytest-style]
@@ -514,6 +518,7 @@ format_on_save = true
[tool.marimo.experimental]
multi_column = true
cache_panel = true
+isolate_apps = true
[tool.marimo.display]
dataframes = "rich"
diff --git a/tests/_session/app_host/__init__.py b/tests/_session/app_host/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/_session/app_host/test_app_host.py b/tests/_session/app_host/test_app_host.py
new file mode 100644
index 0000000000..847d50e71e
--- /dev/null
+++ b/tests/_session/app_host/test_app_host.py
@@ -0,0 +1,510 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import pytest
+
+
+class TestAppHostCommands:
+ def test_commands_roundtrip_json(self) -> None:
+ """All commands must survive JSON encode/decode."""
+ from marimo._config.config import DEFAULT_CONFIG
+ from marimo._runtime.commands import AppMetadata
+ from marimo._session.app_host.commands import (
+ CreateKernelCmd,
+ KernelCreatedResponse,
+ ShutdownAppHostCmd,
+ StopKernelCmd,
+ decode_mgmt_command,
+ decode_mgmt_response,
+ encode_mgmt_command,
+ encode_mgmt_response,
+ )
+
+ app_metadata = AppMetadata(
+ query_params={},
+ cli_args={},
+ app_config={}, # type: ignore[arg-type]
+ )
+ user_config = DEFAULT_CONFIG
+
+ # Test commands
+ commands = [
+ CreateKernelCmd(
+ session_id="s1",
+ configs={},
+ app_metadata=app_metadata,
+ user_config=user_config,
+ virtual_files_supported=True,
+ redirect_console_to_browser=True,
+ log_level=10,
+ ),
+ StopKernelCmd(session_id="s1"),
+ ShutdownAppHostCmd(),
+ ]
+
+ for cmd in commands:
+ data = encode_mgmt_command(cmd)
+ restored = decode_mgmt_command(data)
+ assert type(restored) is type(cmd)
+
+ # Test responses
+ responses = [
+ KernelCreatedResponse(session_id="s1", success=True),
+ KernelCreatedResponse(
+ session_id="s1", success=False, error="boom"
+ ),
+ ]
+
+ for resp in responses:
+ data = encode_mgmt_response(resp)
+ restored = decode_mgmt_response(data)
+ assert type(restored) is type(resp)
+
+
+class TestAppHostOnEmpty:
+ def test_on_empty_fires_when_session_ids_becomes_empty(self) -> None:
+ """on_empty callback fires when all sessions exit."""
+ import threading
+
+ from marimo._session.app_host.host import AppHost
+
+ fired = threading.Event()
+
+ def on_empty() -> None:
+ fired.set()
+
+ app_host = AppHost("/tmp/test_app.py", on_empty=on_empty)
+ # Simulate a kernel being alive
+ app_host._session_ids.add("s1")
+
+ # Simulate receiving a KernelExited message by calling
+ # discard + the callback logic directly (avoids needing
+ # a real subprocess with ZMQ sockets).
+ app_host._session_ids.discard("s1")
+ assert len(app_host._session_ids) == 0
+ # Replicate the callback logic from _stream_receiver_loop
+ callback = app_host._on_empty
+ app_host._on_empty = None
+ if callback is not None:
+ threading.Thread(target=callback, daemon=True).start()
+
+ assert fired.wait(timeout=2), "on_empty callback was not fired"
+
+ def test_on_empty_does_not_fire_when_kernels_remain(self) -> None:
+ """on_empty callback does NOT fire when kernels remain."""
+ import threading
+
+ from marimo._session.app_host.host import AppHost
+
+ fired = threading.Event()
+
+ def on_empty() -> None:
+ fired.set()
+
+ app_host = AppHost("/tmp/test_app.py", on_empty=on_empty)
+ app_host._session_ids.add("s1")
+ app_host._session_ids.add("s2")
+
+ # Remove one — still one left
+ app_host._session_ids.discard("s1")
+ assert len(app_host._session_ids) == 1
+
+ # Replicate the callback logic
+ if not app_host._session_ids:
+ callback = app_host._on_empty
+ app_host._on_empty = None
+ if callback is not None:
+ threading.Thread(target=callback, daemon=True).start()
+
+ assert not fired.wait(timeout=0.5), (
+ "on_empty callback should not fire when kernels remain"
+ )
+
+ def test_on_empty_fires_only_once(self) -> None:
+ """on_empty callback fires at most once (double-fire prevention)."""
+ import threading
+
+ from marimo._session.app_host.host import AppHost
+
+ call_count = 0
+ lock = threading.Lock()
+ done = threading.Event()
+
+ def on_empty() -> None:
+ nonlocal call_count
+ with lock:
+ call_count += 1
+ done.set()
+
+ app_host = AppHost("/tmp/test_app.py", on_empty=on_empty)
+ app_host._session_ids.add("s1")
+ app_host._session_ids.add("s2")
+
+ # Simulate both kernels exiting
+ for sid in ["s1", "s2"]:
+ app_host._session_ids.discard(sid)
+ if not app_host._session_ids:
+ callback = app_host._on_empty
+ app_host._on_empty = None
+ if callback is not None:
+ threading.Thread(target=callback, daemon=True).start()
+
+ assert done.wait(timeout=2)
+ # Give any potential second callback time to run
+ threading.Event().wait(timeout=0.2)
+ with lock:
+ assert call_count == 1, (
+ f"on_empty fired {call_count} times, expected 1"
+ )
+
+
+class TestAppHostPool:
+ def test_create_and_reuse(self) -> None:
+ """Pool creates one host per file and reuses it."""
+ from unittest.mock import patch
+
+ from marimo._session.app_host.pool import AppHostPool
+
+ pool = AppHostPool()
+ with patch("marimo._session.app_host.pool.AppHost") as MockHost:
+ MockHost.return_value.is_alive.return_value = True
+ w1 = pool.get_or_create("/tmp/test_app1.py")
+ w2 = pool.get_or_create("/tmp/test_app1.py")
+ assert w1 is w2
+
+ def test_different_files_get_different_hosts(self) -> None:
+ """Different files get different app hosts."""
+ from unittest.mock import patch
+
+ from marimo._session.app_host.pool import AppHostPool
+
+ pool = AppHostPool()
+ with patch("marimo._session.app_host.pool.AppHost") as MockHost:
+ MockHost.return_value.is_alive.return_value = True
+ # Each call returns a new mock instance
+ MockHost.side_effect = lambda *_a, **_kw: type(
+ MockHost.return_value
+ )()
+ w1 = pool.get_or_create("/tmp/test_app1.py")
+ w2 = pool.get_or_create("/tmp/test_app2.py")
+ assert w1 is not w2
+
+ def test_shutdown_stops_all(self) -> None:
+ """Shutdown terminates all app hosts."""
+ from unittest.mock import MagicMock
+
+ from marimo._session.app_host.pool import AppHostPool
+
+ pool = AppHostPool()
+ w1, w2 = MagicMock(), MagicMock()
+ pool._workers["/tmp/test_app1.py"] = w1
+ pool._workers["/tmp/test_app2.py"] = w2
+
+ pool.shutdown()
+
+ w1.shutdown.assert_called_once()
+ w2.shutdown.assert_called_once()
+ assert len(pool._workers) == 0
+
+
+class TestAppHost:
+ def test_start_and_shutdown(self) -> None:
+ """App host starts and shuts down cleanly."""
+ from marimo._session.app_host.host import AppHost
+
+ app_host = AppHost("/tmp/test_app.py")
+ app_host.start()
+ assert app_host.is_alive()
+ assert app_host.pid is not None
+
+ app_host.shutdown()
+ assert not app_host.is_alive()
+
+
+class TestAppHostSandbox:
+ def test_app_host_stores_sandbox_dir(self) -> None:
+ """AppHost stores sandbox_dir for cleanup on shutdown."""
+ from marimo._session.app_host.host import AppHost
+
+ host = AppHost("/tmp/test.py", sandbox_dir="/tmp/sandbox-abc")
+ assert host._sandbox_dir == "/tmp/sandbox-abc"
+
+ def test_app_host_shutdown_cleans_up_sandbox_dir(self) -> None:
+ """shutdown() calls cleanup_sandbox_dir when sandbox_dir is set."""
+ from unittest.mock import patch
+
+ from marimo._session.app_host.host import AppHost
+
+ host = AppHost("/tmp/test.py", sandbox_dir="/tmp/sandbox-abc")
+
+ with patch("marimo._cli.sandbox.cleanup_sandbox_dir") as mock_cleanup:
+ host.shutdown()
+ mock_cleanup.assert_called_once_with("/tmp/sandbox-abc")
+
+ assert host._sandbox_dir is None
+
+ def test_app_host_shutdown_skips_cleanup_without_sandbox(self) -> None:
+ """shutdown() does not call cleanup when no sandbox_dir."""
+ from unittest.mock import patch
+
+ from marimo._session.app_host.host import AppHost
+
+ host = AppHost("/tmp/test.py")
+
+ with patch("marimo._cli.sandbox.cleanup_sandbox_dir") as mock_cleanup:
+ host.shutdown()
+ mock_cleanup.assert_not_called()
+
+ def test_pool_sandbox_flag_stored(self) -> None:
+ """AppHostPool stores the sandbox flag."""
+ from marimo._session.app_host.pool import AppHostPool
+
+ pool = AppHostPool(sandbox=False)
+ assert pool._sandbox is False
+
+ pool = AppHostPool(sandbox=True)
+ assert pool._sandbox is True
+
+ def test_pool_sandbox_builds_venv_and_passes_to_host(self) -> None:
+ """When sandbox=True, pool builds a venv and passes python/sandbox_dir
+ to AppHost."""
+ from unittest.mock import MagicMock, patch
+
+ from marimo._session.app_host.pool import AppHostPool
+
+ pool = AppHostPool(sandbox=True)
+
+ mock_host = MagicMock()
+ mock_host.is_alive.return_value = True
+
+ with (
+ patch(
+ "marimo._session.app_host.pool.build_sandbox_venv",
+ return_value=(
+ "/tmp/sandbox-xyz",
+ "/tmp/sandbox-xyz/bin/python",
+ ),
+ ) as mock_build,
+ patch(
+ "marimo._session.app_host.pool.get_ipc_kernel_deps",
+ return_value=["pyzmq==26.0.0"],
+ ),
+ patch(
+ "marimo._session.app_host.pool.AppHost",
+ return_value=mock_host,
+ ) as mock_host_cls,
+ ):
+ pool.get_or_create("/tmp/test_app.py")
+
+ # Verify venv was built with correct args
+ mock_build.assert_called_once()
+ _, kwargs = mock_build.call_args
+ assert kwargs["additional_deps"] == ["pyzmq==26.0.0"]
+
+ # Verify AppHost received python and sandbox_dir
+ mock_host_cls.assert_called_once()
+ host_kwargs = mock_host_cls.call_args[1]
+ assert host_kwargs["python"] == "/tmp/sandbox-xyz/bin/python"
+ assert host_kwargs["sandbox_dir"] == "/tmp/sandbox-xyz"
+
+ def test_pool_no_sandbox_skips_venv_build(self) -> None:
+ """When sandbox=False, pool does not build a venv."""
+ from unittest.mock import MagicMock, patch
+
+ from marimo._session.app_host.pool import AppHostPool
+
+ pool = AppHostPool(sandbox=False)
+
+ mock_host = MagicMock()
+ mock_host.is_alive.return_value = True
+
+ with (
+ patch(
+ "marimo._session.app_host.pool.build_sandbox_venv",
+ ) as mock_build,
+ patch(
+ "marimo._session.app_host.pool.AppHost",
+ return_value=mock_host,
+ ) as mock_host_cls,
+ ):
+ pool.get_or_create("/tmp/test_app.py")
+
+ mock_build.assert_not_called()
+
+ # AppHost should get python=None, sandbox_dir=None
+ host_kwargs = mock_host_cls.call_args[1]
+ assert host_kwargs.get("python") is None
+ assert host_kwargs.get("sandbox_dir") is None
+
+ def test_pool_sandbox_race_cleans_up_duplicate_venv(self) -> None:
+ """If another thread creates the host while we build the venv,
+ the duplicate venv is cleaned up."""
+ from unittest.mock import MagicMock, patch
+
+ from marimo._session.app_host.pool import AppHostPool
+
+ pool = AppHostPool(sandbox=True)
+
+ # Pre-populate pool with an alive host (simulates another thread)
+ existing_host = MagicMock()
+ existing_host.is_alive.return_value = True
+
+ # Simulate the race: first get_or_create finds no host, drops
+ # the lock to build the venv, then re-acquires and finds a host
+ # that another thread created. We do this by injecting the host
+ # into pool._workers during the build_sandbox_venv call.
+ def build_and_inject(
+ filename: str,
+ additional_deps: list[str] | None = None, # noqa: ARG001
+ ) -> tuple[str, str]:
+ import os
+
+ abs_path = os.path.abspath(filename)
+ pool._workers[abs_path] = existing_host
+ return ("/tmp/sandbox-dup", "/tmp/sandbox-dup/bin/python")
+
+ with (
+ patch(
+ "marimo._session.app_host.pool.build_sandbox_venv",
+ side_effect=build_and_inject,
+ ),
+ patch(
+ "marimo._session.app_host.pool.get_ipc_kernel_deps",
+ return_value=[],
+ ),
+ patch(
+ "marimo._session.app_host.pool.cleanup_sandbox_dir",
+ ) as mock_cleanup,
+ ):
+ result = pool.get_or_create("/tmp/test_app.py")
+ assert result is existing_host
+ mock_cleanup.assert_called_once_with("/tmp/sandbox-dup")
+
+
+class TestAppHostQueueManager:
+ def test_stream_queue_is_regular_queue(self) -> None:
+ """AppHostQueueManager's stream_queue is a regular queue.Queue."""
+ import queue
+
+ from marimo._session.app_host.host import AppHost
+ from marimo._session.managers.app_host import AppHostQueueManager
+
+ # No need to start a real subprocess — register_stream and
+ # unregister_stream only use the in-memory dict from __init__.
+ app_host = AppHost("/tmp/test_app.py")
+ qm = AppHostQueueManager(app_host, "s1")
+ assert isinstance(qm.stream_queue, queue.Queue)
+ assert qm.win32_interrupt_queue is None
+
+ # close_queues puts None sentinel for QueueDistributor
+ qm.close_queues()
+ assert qm.stream_queue.get_nowait() is None
+
+
+class TestAppHostMultipleClients:
+ def test_create_session_uses_per_client_session_id(self) -> None:
+ """SessionImpl.create() must pass the per-client session_id — not
+ the shared initialization_id (file_key) — to the AppHost managers.
+
+ Regression test: previously initialization_id was used as the
+ multiplexing key, so two clients of the same notebook would share
+ a key and the second register_stream call would overwrite the
+ first's queue.
+ """
+ from unittest.mock import Mock, patch
+
+ from marimo._config.config import DEFAULT_CONFIG
+ from marimo._session.app_host import AppHostContext
+ from marimo._session.app_host.host import AppHost
+ from marimo._session.model import SessionMode
+ from marimo._session.session import SessionImpl
+
+ app_host = AppHost("/tmp/test_app.py")
+ pool = Mock()
+ pool.get_or_create.return_value = app_host
+
+ file_key = "/tmp/test_app.py"
+
+ with patch(
+ "marimo._session.managers.app_host."
+ "AppHostKernelManager.start_kernel"
+ ):
+ for sid in ("session-1", "session-2"):
+ SessionImpl.create(
+ initialization_id=file_key,
+ session_consumer=Mock(),
+ mode=SessionMode.RUN,
+ app_metadata=Mock(),
+ app_file_manager=Mock(path="/tmp/test_app.py"),
+ config_manager=Mock(
+ with_overrides=Mock(
+ return_value=Mock(
+ get_config=Mock(return_value=DEFAULT_CONFIG)
+ )
+ )
+ ),
+ virtual_files_supported=True,
+ redirect_console_to_browser=False,
+ ttl_seconds=None,
+ auto_instantiate=False,
+ app_host_context=AppHostContext(pool=pool, session_id=sid),
+ )
+
+ # Both session IDs must be registered independently.
+ with app_host._stream_lock:
+ assert "session-1" in app_host._stream_receivers
+ assert "session-2" in app_host._stream_receivers
+ assert (
+ app_host._stream_receivers["session-1"]
+ is not app_host._stream_receivers["session-2"]
+ )
+
+
+class TestAppHostKernelManager:
+ def test_satisfies_kernel_manager_protocol(self) -> None:
+ """AppHostKernelManager has all required KernelManager attributes."""
+ from unittest.mock import Mock
+
+ from marimo._session.app_host.host import AppHost
+ from marimo._session.managers.app_host import (
+ AppHostKernelManager,
+ AppHostQueueManager,
+ )
+ from marimo._session.model import SessionMode
+
+ # No need to start a real subprocess — an unstarted AppHost
+ # is sufficient to verify the protocol surface.
+ app_host = AppHost("/tmp/test.py")
+ qm = AppHostQueueManager(app_host, "s1")
+ mgr = AppHostKernelManager(
+ app_host=app_host,
+ session_id="s1",
+ queue_manager=qm,
+ mode=SessionMode.RUN,
+ configs={},
+ app_metadata=Mock(),
+ config_manager=Mock(),
+ redirect_console_to_browser=True,
+ )
+
+ # Check protocol attributes exist
+ assert mgr.kernel_task is None
+ assert mgr.mode == SessionMode.RUN
+ assert mgr.pid is None # no subprocess started
+ assert mgr.profile_path is None
+ assert not mgr.is_alive() # no subprocess started
+
+ # interrupt_kernel is a no-op
+ mgr.interrupt_kernel()
+
+ # kernel_connection raises
+ with pytest.raises(NotImplementedError):
+ _ = mgr.kernel_connection
diff --git a/tests/_session/app_host/test_main.py b/tests/_session/app_host/test_main.py
new file mode 100644
index 0000000000..8485512e5c
--- /dev/null
+++ b/tests/_session/app_host/test_main.py
@@ -0,0 +1,281 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import pickle
+import queue
+from unittest.mock import Mock, patch
+
+import pytest
+
+from marimo._config.config import DEFAULT_CONFIG
+from marimo._runtime.commands import AppMetadata, StopKernelCommand
+from marimo._session.app_host.commands import (
+ Channel,
+ CreateKernelCmd,
+ KernelCreatedResponse,
+ StopKernelCmd,
+ decode_mgmt_response,
+)
+from marimo._session.app_host.main import (
+ _handle_command,
+ _handle_create_kernel,
+ _handle_stop_kernel,
+ _KernelInfo,
+ _KernelQueues,
+ _shutdown_all_kernels,
+ _stream_collector_loop,
+ _TaggedStreamQueue,
+)
+
+
+class TestTaggedStreamQueue:
+ def test_put_tags_item_with_session_id(self) -> None:
+ outbox: queue.Queue[object] = queue.Queue()
+ tsq = _TaggedStreamQueue("s1", outbox)
+ tsq.put("hello")
+ assert outbox.get_nowait() == ("s1", "hello")
+
+ def test_put_nowait_tags_item_with_session_id(self) -> None:
+ outbox: queue.Queue[object] = queue.Queue()
+ tsq = _TaggedStreamQueue("s1", outbox)
+ tsq.put_nowait("hello")
+ assert outbox.get_nowait() == ("s1", "hello")
+
+ def test_get_raises_not_implemented(self) -> None:
+ tsq = _TaggedStreamQueue("s1", queue.Queue())
+ with pytest.raises(NotImplementedError):
+ tsq.get()
+
+ def test_get_nowait_raises_not_implemented(self) -> None:
+ tsq = _TaggedStreamQueue("s1", queue.Queue())
+ with pytest.raises(NotImplementedError):
+ tsq.get_nowait()
+
+ def test_empty_always_returns_true(self) -> None:
+ outbox: queue.Queue[object] = queue.Queue()
+ tsq = _TaggedStreamQueue("s1", outbox)
+ tsq.put("something")
+ assert tsq.empty() is True
+
+
+class TestHandleCommand:
+ def _make_kernel_info(
+ self, session_id: str = "s1"
+ ) -> tuple[_KernelInfo, _KernelQueues]:
+ queues = _KernelQueues(
+ control=queue.Queue(),
+ ui_element=queue.Queue(),
+ completion=queue.Queue(),
+ input=queue.Queue(),
+ )
+ info = _KernelInfo(thread=Mock(), queues=queues, session_id=session_id)
+ return info, queues
+
+ def _make_cmd_socket(
+ self, session_id: str, channel: Channel, payload: object
+ ) -> Mock:
+ sock = Mock()
+ sock.recv_multipart.return_value = [
+ session_id.encode(),
+ channel.value,
+ pickle.dumps(payload),
+ ]
+ return sock
+
+ def test_routes_to_control_queue(self) -> None:
+ info, queues = self._make_kernel_info()
+ sock = self._make_cmd_socket("s1", Channel.CONTROL, "ctrl_payload")
+ _handle_command(sock, {"s1": info})
+ assert queues.control.get_nowait() == "ctrl_payload"
+
+ def test_routes_to_ui_element_queue(self) -> None:
+ info, queues = self._make_kernel_info()
+ sock = self._make_cmd_socket("s1", Channel.UI_ELEMENT, "ui_payload")
+ _handle_command(sock, {"s1": info})
+ assert queues.ui_element.get_nowait() == "ui_payload"
+
+ def test_routes_to_completion_queue(self) -> None:
+ info, queues = self._make_kernel_info()
+ sock = self._make_cmd_socket("s1", Channel.COMPLETION, "comp_payload")
+ _handle_command(sock, {"s1": info})
+ assert queues.completion.get_nowait() == "comp_payload"
+
+ def test_routes_to_input_queue(self) -> None:
+ info, queues = self._make_kernel_info()
+ sock = self._make_cmd_socket("s1", Channel.INPUT, "input_payload")
+ _handle_command(sock, {"s1": info})
+ assert queues.input.get_nowait() == "input_payload"
+
+ def test_drops_command_for_unknown_session(self) -> None:
+ """No error when session_id is not in the registry."""
+ sock = self._make_cmd_socket("unknown", Channel.CONTROL, "payload")
+ _handle_command(sock, {}) # empty registry
+
+ def test_unknown_channel_raises_value_error(self) -> None:
+ """Unknown channel bytes raise ValueError from Channel enum."""
+ info, _ = self._make_kernel_info()
+ sock = Mock()
+ sock.recv_multipart.return_value = [
+ b"s1",
+ b"bogus",
+ pickle.dumps("payload"),
+ ]
+ with pytest.raises(ValueError):
+ _handle_command(sock, {"s1": info})
+
+
+class TestHandleStopKernel:
+ def test_removes_from_registry_and_sends_stop_command(self) -> None:
+ queues = _KernelQueues(
+ control=queue.Queue(),
+ ui_element=queue.Queue(),
+ completion=queue.Queue(),
+ input=queue.Queue(),
+ )
+ info = _KernelInfo(thread=Mock(), queues=queues, session_id="s1")
+ kernels = {"s1": info}
+
+ _handle_stop_kernel(StopKernelCmd(session_id="s1"), kernels)
+
+ assert "s1" not in kernels
+ assert isinstance(queues.control.get_nowait(), StopKernelCommand)
+
+ def test_noop_for_unknown_session(self) -> None:
+ _handle_stop_kernel(StopKernelCmd(session_id="unknown"), {})
+
+
+class TestHandleCreateKernelFailure:
+ def test_failure_sends_error_response(self) -> None:
+ cmd = CreateKernelCmd(
+ session_id="s1",
+ configs={},
+ app_metadata=AppMetadata(
+ query_params={},
+ cli_args={},
+ app_config={}, # type: ignore[arg-type]
+ ),
+ user_config=DEFAULT_CONFIG,
+ virtual_files_supported=True,
+ redirect_console_to_browser=True,
+ log_level=10,
+ )
+ kernels: dict[str, _KernelInfo] = {}
+ outbox: queue.Queue[object] = queue.Queue()
+ response_socket = Mock()
+
+ with patch(
+ "marimo._session.app_host.main.threading.Thread",
+ side_effect=RuntimeError("thread failed"),
+ ):
+ _handle_create_kernel(cmd, kernels, outbox, response_socket)
+
+ assert len(kernels) == 0
+ response_socket.send.assert_called_once()
+ resp = decode_mgmt_response(response_socket.send.call_args[0][0])
+ assert isinstance(resp, KernelCreatedResponse)
+ assert resp.success is False
+ assert resp.session_id == "s1"
+ assert "thread failed" in (resp.error or "")
+
+
+class TestStreamCollectorLoop:
+ def test_reads_outbox_and_sends_over_socket(self) -> None:
+ outbox: queue.Queue[object] = queue.Queue()
+ stream_socket = Mock()
+
+ outbox.put(("s1", "hello"))
+ outbox.put(None) # stop sentinel
+
+ _stream_collector_loop(outbox, stream_socket)
+
+ stream_socket.send_multipart.assert_called_once_with(
+ [b"s1", pickle.dumps("hello")]
+ )
+
+ def test_stops_on_none_sentinel(self) -> None:
+ outbox: queue.Queue[object] = queue.Queue()
+ stream_socket = Mock()
+
+ outbox.put(None)
+ _stream_collector_loop(outbox, stream_socket)
+
+ stream_socket.send_multipart.assert_not_called()
+
+ def test_continues_on_send_exception(self) -> None:
+ outbox: queue.Queue[object] = queue.Queue()
+ stream_socket = Mock()
+ stream_socket.send_multipart.side_effect = [
+ RuntimeError("send failed"),
+ None,
+ ]
+
+ outbox.put(("s1", "msg1"))
+ outbox.put(("s2", "msg2"))
+ outbox.put(None)
+
+ _stream_collector_loop(outbox, stream_socket)
+
+ assert stream_socket.send_multipart.call_count == 2
+ stream_socket.send_multipart.assert_any_call(
+ [b"s1", pickle.dumps("msg1")]
+ )
+ stream_socket.send_multipart.assert_any_call(
+ [b"s2", pickle.dumps("msg2")]
+ )
+
+
+class TestShutdownAllKernels:
+ def test_sends_stop_command_to_all_kernels(self) -> None:
+ queues1 = _KernelQueues(
+ control=queue.Queue(),
+ ui_element=queue.Queue(),
+ completion=queue.Queue(),
+ input=queue.Queue(),
+ )
+ queues2 = _KernelQueues(
+ control=queue.Queue(),
+ ui_element=queue.Queue(),
+ completion=queue.Queue(),
+ input=queue.Queue(),
+ )
+ kernels = {
+ "s1": _KernelInfo(thread=Mock(), queues=queues1, session_id="s1"),
+ "s2": _KernelInfo(thread=Mock(), queues=queues2, session_id="s2"),
+ }
+
+ _shutdown_all_kernels(kernels)
+
+ assert isinstance(queues1.control.get_nowait(), StopKernelCommand)
+ assert isinstance(queues2.control.get_nowait(), StopKernelCommand)
+ assert len(kernels) == 0
+
+ def test_continues_on_exception_and_clears(self) -> None:
+ bad_queue = Mock()
+ bad_queue.put.side_effect = RuntimeError("put failed")
+ queues1 = _KernelQueues(
+ control=bad_queue,
+ ui_element=queue.Queue(),
+ completion=queue.Queue(),
+ input=queue.Queue(),
+ )
+ queues2 = _KernelQueues(
+ control=queue.Queue(),
+ ui_element=queue.Queue(),
+ completion=queue.Queue(),
+ input=queue.Queue(),
+ )
+ kernels = {
+ "s1": _KernelInfo(thread=Mock(), queues=queues1, session_id="s1"),
+ "s2": _KernelInfo(thread=Mock(), queues=queues2, session_id="s2"),
+ }
+
+ _shutdown_all_kernels(kernels)
+
+ assert isinstance(queues2.control.get_nowait(), StopKernelCommand)
+ assert len(kernels) == 0
diff --git a/tests/_session/app_host/test_pool.py b/tests/_session/app_host/test_pool.py
new file mode 100644
index 0000000000..d997ed30ff
--- /dev/null
+++ b/tests/_session/app_host/test_pool.py
@@ -0,0 +1,35 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import os
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from marimo._session.app_host.pool import AppHostPool
+
+
+class TestAppHostPoolRespawnDead:
+ def test_respawns_dead_host(self) -> None:
+ """_create_locked shuts down dead host and creates a new one."""
+ pool = AppHostPool(sandbox=False)
+
+ dead_host = MagicMock()
+ dead_host.is_alive.return_value = False
+
+ new_host = MagicMock()
+ new_host.is_alive.return_value = True
+
+ abs_path = os.path.abspath("/tmp/test_respawn.py")
+ pool._workers[abs_path] = dead_host
+
+ with patch(
+ "marimo._session.app_host.pool.AppHost",
+ return_value=new_host,
+ ):
+ result = pool.get_or_create("/tmp/test_respawn.py")
+
+ dead_host.shutdown.assert_called_once()
+ assert result is new_host
+ assert pool._workers[abs_path] is new_host
diff --git a/tests/_session/managers/test_app_host.py b/tests/_session/managers/test_app_host.py
new file mode 100644
index 0000000000..d2cdb7d276
--- /dev/null
+++ b/tests/_session/managers/test_app_host.py
@@ -0,0 +1,169 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from unittest.mock import Mock, PropertyMock
+
+import pytest
+
+from marimo._session.app_host.commands import KernelCreatedResponse
+from marimo._session.managers.app_host import (
+ AppHostKernelManager,
+ AppHostQueueManager,
+ _AppHostLike,
+ _AppHostPushQueue,
+)
+from marimo._session.model import SessionMode
+
+
+class TestAppHostPushQueue:
+ def test_put_calls_send_command(self) -> None:
+ app_host = Mock()
+ q = _AppHostPushQueue(app_host, "s1", "control")
+ q.put("payload")
+ app_host.send_command.assert_called_once_with(
+ "s1", "control", "payload"
+ )
+
+ def test_put_nowait_calls_send_command(self) -> None:
+ app_host = Mock()
+ q = _AppHostPushQueue(app_host, "s1", "control")
+ q.put_nowait("payload")
+ app_host.send_command.assert_called_once_with(
+ "s1", "control", "payload"
+ )
+
+ def test_get_raises_not_implemented(self) -> None:
+ q = _AppHostPushQueue(Mock(), "s1", "control")
+ with pytest.raises(NotImplementedError):
+ q.get()
+
+ def test_get_nowait_raises_not_implemented(self) -> None:
+ q = _AppHostPushQueue(Mock(), "s1", "control")
+ with pytest.raises(NotImplementedError):
+ q.get_nowait()
+
+ def test_empty_always_returns_true(self) -> None:
+ q = _AppHostPushQueue(Mock(), "s1", "control")
+ assert q.empty() is True
+
+
+class TestPutControlRequestDelegation:
+ """Verify AppHostQueueManager.put_control_request delegates correctly.
+
+ Detailed routing logic is tested in tests/_session/test_queue.py.
+ """
+
+ def test_delegates_to_route_control_request(self) -> None:
+ from marimo._runtime.commands import StopKernelCommand
+
+ app_host = Mock()
+ qm = AppHostQueueManager(app_host, "s1")
+ qm.control_queue = Mock()
+ qm.completion_queue = Mock()
+ qm.set_ui_element_queue = Mock()
+
+ cmd = StopKernelCommand()
+ qm.put_control_request(cmd)
+
+ qm.control_queue.put.assert_called_once_with(cmd)
+ qm.completion_queue.put.assert_not_called()
+ qm.set_ui_element_queue.put.assert_not_called()
+
+
+class TestAppHostLike:
+ def test_pid_delegates_to_app_host(self) -> None:
+ app_host = Mock()
+ type(app_host).pid = PropertyMock(return_value=1234)
+ like = _AppHostLike(app_host, "s1")
+ assert like.pid == 1234
+
+ def test_is_alive_delegates_to_has_active_session(self) -> None:
+ app_host = Mock()
+ app_host.has_active_session.return_value = True
+ like = _AppHostLike(app_host, "s1")
+ assert like.is_alive() is True
+ app_host.has_active_session.assert_called_once_with("s1")
+
+ def test_terminate_is_noop(self) -> None:
+ like = _AppHostLike(Mock(), "s1")
+ like.terminate() # should not raise
+
+ def test_join_is_noop(self) -> None:
+ like = _AppHostLike(Mock(), "s1")
+ like.join(timeout=1.0) # should not raise
+
+
+class TestAppHostKernelManagerStartAndClose:
+ def test_start_kernel_sets_kernel_task(self) -> None:
+ app_host = Mock()
+ app_host.create_kernel.return_value = KernelCreatedResponse(
+ session_id="s1", success=True
+ )
+
+ config_manager = Mock()
+ config_manager.get_config.return_value = {}
+
+ mgr = AppHostKernelManager(
+ app_host=app_host,
+ session_id="s1",
+ queue_manager=Mock(),
+ mode=SessionMode.RUN,
+ configs={},
+ app_metadata=Mock(),
+ config_manager=config_manager,
+ redirect_console_to_browser=True,
+ )
+
+ mgr.start_kernel()
+
+ app_host.create_kernel.assert_called_once()
+ assert isinstance(mgr.kernel_task, _AppHostLike)
+
+ def test_start_kernel_failure_raises(self) -> None:
+ app_host = Mock()
+ app_host.create_kernel.return_value = KernelCreatedResponse(
+ session_id="s1", success=False, error="boom"
+ )
+
+ config_manager = Mock()
+ config_manager.get_config.return_value = {}
+
+ mgr = AppHostKernelManager(
+ app_host=app_host,
+ session_id="s1",
+ queue_manager=Mock(),
+ mode=SessionMode.RUN,
+ configs={},
+ app_metadata=Mock(),
+ config_manager=config_manager,
+ redirect_console_to_browser=True,
+ )
+
+ with pytest.raises(RuntimeError, match="boom"):
+ mgr.start_kernel()
+
+ assert mgr.kernel_task is None
+
+ def test_close_kernel_calls_close_queues_and_stop_kernel(self) -> None:
+ app_host = Mock()
+ queue_manager = Mock()
+
+ mgr = AppHostKernelManager(
+ app_host=app_host,
+ session_id="s1",
+ queue_manager=queue_manager,
+ mode=SessionMode.RUN,
+ configs={},
+ app_metadata=Mock(),
+ config_manager=Mock(),
+ redirect_console_to_browser=True,
+ )
+
+ mgr.close_kernel()
+
+ queue_manager.close_queues.assert_called_once()
+ app_host.stop_kernel.assert_called_once_with("s1")
diff --git a/tests/_session/test_queue.py b/tests/_session/test_queue.py
new file mode 100644
index 0000000000..5a2b921f81
--- /dev/null
+++ b/tests/_session/test_queue.py
@@ -0,0 +1,62 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from unittest.mock import Mock
+
+from marimo._runtime.commands import (
+ CodeCompletionCommand,
+ ModelCommand,
+ ModelUpdateMessage,
+ StopKernelCommand,
+ UpdateUIElementCommand,
+)
+from marimo._session.queue import route_control_request
+
+
+class TestRouteControlRequest:
+ def _make_queues(self) -> tuple[Mock, Mock, Mock]:
+ return Mock(), Mock(), Mock()
+
+ def test_completion_goes_to_completion_queue_only(self) -> None:
+ control, completion, ui_element = self._make_queues()
+ cmd = CodeCompletionCommand(id="r1", document="x.", cell_id="c1")
+
+ route_control_request(cmd, control, completion, ui_element)
+
+ completion.put.assert_called_once_with(cmd)
+ control.put.assert_not_called()
+ ui_element.put.assert_not_called()
+
+ def test_ui_element_goes_to_both_queues(self) -> None:
+ control, completion, ui_element = self._make_queues()
+ cmd = UpdateUIElementCommand(object_ids=["ui1"], values=[42])
+
+ route_control_request(cmd, control, completion, ui_element)
+
+ control.put.assert_called_once_with(cmd)
+ ui_element.put.assert_called_once_with(cmd)
+ completion.put.assert_not_called()
+
+ def test_model_command_goes_to_both_queues(self) -> None:
+ control, completion, ui_element = self._make_queues()
+ cmd = ModelCommand(
+ model_id="m1",
+ message=ModelUpdateMessage(state={}, buffer_paths=[]),
+ buffers=[],
+ )
+
+ route_control_request(cmd, control, completion, ui_element)
+
+ control.put.assert_called_once_with(cmd)
+ ui_element.put.assert_called_once_with(cmd)
+ completion.put.assert_not_called()
+
+ def test_regular_command_goes_to_control_queue_only(self) -> None:
+ control, completion, ui_element = self._make_queues()
+ cmd = StopKernelCommand()
+
+ route_control_request(cmd, control, completion, ui_element)
+
+ control.put.assert_called_once_with(cmd)
+ completion.put.assert_not_called()
+ ui_element.put.assert_not_called()
diff --git a/tests/snapshots/dependencies.txt b/tests/snapshots/dependencies.txt
index 4209c47449..9524422e04 100644
--- a/tests/snapshots/dependencies.txt
+++ b/tests/snapshots/dependencies.txt
@@ -11,6 +11,7 @@ psutil>=5.0
pygments>=2.19,<3
pymdown-extensions>=10.15,<11
pyyaml>=6.0.1
+pyzmq>=27.1.0; python_version < '3.15'
starlette>=0.37.2
tomlkit>=0.12.0
typing_extensions>=4.4.0; python_version < '3.11'