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.

improvement: enable reading session cache in App Mode (configurable) (#7895)

Julian Popescud85e9b766660
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index 079a8e7fae..6c18853eda 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -152,6 +152,8 @@ class RuntimeConfig(TypedDict):
affected cells as stale, `"autorun"` automatically runs affected cells.
- `output_max_bytes`: the maximum size in bytes of cell outputs; larger
values may affect frontend performance
+ - `serve_cached_sessions_in_apps`: if `True`, initialize applications with session cache.
+ The default is `False`.
- `std_stream_max_bytes`: the maximum size in bytes of console outputs;
larger values may affect frontend performance
- `pythonpath`: a list of directories to add to the Python search path.
@@ -177,6 +179,7 @@ class RuntimeConfig(TypedDict):
on_cell_change: OnCellChangeType
watcher_on_save: Literal["lazy", "autorun"]
output_max_bytes: int
+ serve_cached_sessions_in_apps: NotRequired[bool]
std_stream_max_bytes: int
pythonpath: NotRequired[list[str]]
dotenv: NotRequired[list[str]]
@@ -774,15 +777,18 @@ def merge_config(
# Patches for backward compatibility
if "runtime" in merged:
if (
- merged["runtime"].get("auto_reload") is False # type:ignore[comparison-overlap]
+ merged["runtime"].get("auto_reload")
+ is False # type:ignore[comparison-overlap]
):
merged["runtime"]["auto_reload"] = "off"
elif (
- merged["runtime"].get("auto_reload") is True # type:ignore[comparison-overlap]
+ merged["runtime"].get("auto_reload")
+ is True # type:ignore[comparison-overlap]
):
merged["runtime"]["auto_reload"] = "lazy"
elif (
- merged["runtime"].get("auto_reload") == "detect" # type:ignore[comparison-overlap]
+ merged["runtime"].get("auto_reload")
+ == "detect" # type:ignore[comparison-overlap]
):
merged["runtime"]["auto_reload"] = "lazy"
diff --git a/marimo/_pyodide/bootstrap.py b/marimo/_pyodide/bootstrap.py
index 7a301aaaf5..57f0771010 100644
--- a/marimo/_pyodide/bootstrap.py
+++ b/marimo/_pyodide/bootstrap.py
@@ -54,6 +54,7 @@ def instantiate(
session.put_control_request(
CreateNotebookCommand(
execution_requests=execution_requests,
+ cell_ids=tuple(app.cell_manager.cell_ids()),
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[], values=[], request=None
),
diff --git a/marimo/_runtime/commands.py b/marimo/_runtime/commands.py
index 577fe2ebf6..e2d03503f7 100644
--- a/marimo/_runtime/commands.py
+++ b/marimo/_runtime/commands.py
@@ -488,12 +488,14 @@ class CreateNotebookCommand(Command):
Attributes:
execution_requests: ExecuteCellCommand for each notebook cell.
+ cell_ids: Initial cell IDs in the notebook.
set_ui_element_value_request: Initial UI element values.
auto_run: Whether to automatically execute cells on instantiation.
request: HTTP request context if available.
"""
execution_requests: tuple[ExecuteCellCommand, ...]
+ cell_ids: tuple[CellId_t, ...]
set_ui_element_value_request: UpdateUIElementCommand
auto_run: bool
request: Optional[HTTPRequest] = None
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 88e5ebf219..ce9c68c455 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -69,6 +69,7 @@ from marimo._messaging.notification import (
SQLMetadata,
SQLTableListPreviewNotification,
SQLTablePreviewNotification,
+ UpdateCellIdsNotification,
ValidateSQLResultNotification,
VariableDeclarationNotification,
VariablesNotification,
@@ -2111,6 +2112,10 @@ class Kernel:
LOGGER.info("App is already instantiated, skipping instantiation.")
return
+ broadcast_notification(
+ UpdateCellIdsNotification(cell_ids=list(request.cell_ids))
+ )
+
# Handle markdown cells specially during kernel-ready initialization
execution_requests = {
er.cell_id: er for er in request.execution_requests
diff --git a/marimo/_session/extensions/extensions.py b/marimo/_session/extensions/extensions.py
index 095433a29f..f63e4b8af2 100644
--- a/marimo/_session/extensions/extensions.py
+++ b/marimo/_session/extensions/extensions.py
@@ -8,6 +8,7 @@ Extensions provide a way to add cross-cutting concerns to sessions
from __future__ import annotations
import asyncio
+from enum import Enum
from typing import TYPE_CHECKING, Optional
from marimo import _loggers
@@ -44,6 +45,11 @@ if TYPE_CHECKING:
LOGGER = _loggers.marimo_logger()
+class CacheMode(Enum):
+ READ = "read"
+ READ_WRITE = "write"
+
+
class HeartbeatExtension(SessionExtension):
"""Extension for monitoring kernel health and handling kernel death.
@@ -111,15 +117,18 @@ class CachingExtension(SessionExtension, SessionEventListener):
*,
enabled: bool,
interval: int = SESSION_CACHE_INTERVAL_SECONDS,
+ mode: CacheMode = CacheMode.READ_WRITE,
) -> None:
"""Initialize the caching extension.
Args:
enabled: Whether to enable caching
interval: How often to write cache (in seconds)
+ mode: Whether to read cache only or read/write.
"""
self.interval = interval
self.enabled = enabled
+ self.mode = mode
self.session_cache_manager: Optional[SessionCacheManager] = None
self.event_bus: Optional[SessionEventBus] = None
@@ -155,7 +164,8 @@ class CachingExtension(SessionExtension, SessionEventListener):
)
# Start the background task to write the session view to disk
- self.session_cache_manager.start()
+ if self.mode is CacheMode.READ_WRITE:
+ self.session_cache_manager.start()
def on_detach(self) -> None:
"""Stop cache manager when detached."""
@@ -169,6 +179,8 @@ class CachingExtension(SessionExtension, SessionEventListener):
) -> None:
"""Rename the path for the cache manager."""
del old_path
+ if self.mode is not CacheMode.READ_WRITE:
+ return None
path = session.app_file_manager.path
if self.session_cache_manager and path:
self.session_cache_manager.rename_path(path)
diff --git a/marimo/_session/session.py b/marimo/_session/session.py
index 4ba3c60e2f..984fba4998 100644
--- a/marimo/_session/session.py
+++ b/marimo/_session/session.py
@@ -29,6 +29,7 @@ from marimo._runtime.commands import (
from marimo._session.consumer import SessionConsumer
from marimo._session.events import SessionEventBus
from marimo._session.extensions.extensions import (
+ CacheMode,
CachingExtension,
HeartbeatExtension,
LoggingExtension,
@@ -141,12 +142,22 @@ class SessionImpl(Session):
redirect_console_to_browser=redirect_console_to_browser,
)
+ if mode == SessionMode.EDIT:
+ cache_enabled = not auto_instantiate
+ cache_mode = CacheMode.READ_WRITE
+ else:
+ cache_enabled = config_manager.get_config()["runtime"].get(
+ "serve_cached_sessions_in_apps", False
+ )
+ cache_mode = CacheMode.READ
+
extensions = [
*(extensions or []),
LoggingExtension(),
HeartbeatExtension(),
CachingExtension(
- enabled=not auto_instantiate and mode == SessionMode.EDIT
+ enabled=cache_enabled,
+ mode=cache_mode,
),
NotificationListenerExtension(
kernel_manager=kernel_manager, queue_manager=queue_manager
@@ -360,13 +371,12 @@ class SessionImpl(Session):
http_request: Optional[HTTPRequest],
) -> None:
"""Instantiate the app."""
+ app = self.app_file_manager.app
# If codes are provided, use them instead of the file codes
# This is used when the frontend has local edits that should be
# used instead of the stored file (e.g. local editing before connecting).
- codes = (
- request.codes or self.app_file_manager.app.cell_manager.code_map()
- )
+ codes = request.codes or app.cell_manager.code_map()
execution_requests = tuple(
ExecuteCellCommand(
@@ -380,6 +390,7 @@ class SessionImpl(Session):
self.put_control_request(
CreateNotebookCommand(
execution_requests=execution_requests,
+ cell_ids=tuple(app.cell_manager.cell_ids()),
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=request.object_ids,
values=request.values,
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index 02168e8889..4b8e0d334b 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -825,12 +825,16 @@ components:
description: "Instantiate and initialize a notebook.\n\n Sent when a notebook\
\ is first loaded. Contains all cells and initial UI element values.\n\n \
\ Attributes:\n execution_requests: ExecuteCellCommand for each notebook\
- \ cell.\n set_ui_element_value_request: Initial UI element values.\n\
- \ auto_run: Whether to automatically execute cells on instantiation.\n\
- \ request: HTTP request context if available."
+ \ cell.\n cell_ids: Initial cell IDs in the notebook.\n set_ui_element_value_request:\
+ \ Initial UI element values.\n auto_run: Whether to automatically execute\
+ \ cells on instantiation.\n request: HTTP request context if available."
properties:
autoRun:
type: boolean
+ cellIds:
+ items:
+ type: string
+ type: array
executionRequests:
items:
$ref: '#/components/schemas/ExecuteCellCommand'
@@ -848,6 +852,7 @@ components:
required:
- type
- executionRequests
+ - cellIds
- setUiElementValueRequest
- autoRun
title: CreateNotebookCommand
@@ -3700,14 +3705,16 @@ components:
\ file changes when saving. `\"lazy\"` marks\n affected cells as stale,\
\ `\"autorun\"` automatically runs affected cells.\n - `output_max_bytes`:\
\ the maximum size in bytes of cell outputs; larger\n values may affect\
- \ frontend performance\n - `std_stream_max_bytes`: the maximum size in\
- \ bytes of console outputs;\n larger values may affect frontend performance\n\
- \ - `pythonpath`: a list of directories to add to the Python search path.\n\
- \ Directories will be added to the head of sys.path. Similar to the\n\
- \ `PYTHONPATH` environment variable, the directories will be included\
- \ in\n where Python will look for imported modules.\n - `dotenv`:\
- \ a list of paths to `.env` files to load.\n If the file does not exist,\
- \ it will be silently ignored.\n The default is `[\".env\"]` if a pyproject.toml\
+ \ frontend performance\n - `serve_cached_sessions_in_apps`: if `True`,\
+ \ initialize applications with session cache.\n The default is `False`.\n\
+ \ - `std_stream_max_bytes`: the maximum size in bytes of console outputs;\n\
+ \ larger values may affect frontend performance\n - `pythonpath`:\
+ \ a list of directories to add to the Python search path.\n Directories\
+ \ will be added to the head of sys.path. Similar to the\n `PYTHONPATH`\
+ \ environment variable, the directories will be included in\n where\
+ \ Python will look for imported modules.\n - `dotenv`: a list of paths\
+ \ to `.env` files to load.\n If the file does not exist, it will be\
+ \ silently ignored.\n The default is `[\".env\"]` if a pyproject.toml\
\ is found, otherwise `[]`.\n - `default_sql_output`: the default output\
\ format for SQL queries. Can be one of:\n `\"auto\"`, `\"native\"\
`, `\"polars\"`, `\"lazy-polars\"`, or `\"pandas\"`.\n The default\
@@ -3755,6 +3762,8 @@ components:
type: array
reactive_tests:
type: boolean
+ serve_cached_sessions_in_apps:
+ type: boolean
std_stream_max_bytes:
type: integer
watcher_on_save:
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index fa18303d87..adffc799ef 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -3572,12 +3572,14 @@ export interface components {
*
* Attributes:
* execution_requests: ExecuteCellCommand for each notebook cell.
+ * cell_ids: Initial cell IDs in the notebook.
* set_ui_element_value_request: Initial UI element values.
* auto_run: Whether to automatically execute cells on instantiation.
* request: HTTP request context if available.
*/
CreateNotebookCommand: {
autoRun: boolean;
+ cellIds: string[];
executionRequests: components["schemas"]["ExecuteCellCommand"][];
/** @default null */
request?: components["schemas"]["HTTPRequest"] | null;
@@ -5288,6 +5290,8 @@ export interface components {
* affected cells as stale, `"autorun"` automatically runs affected cells.
* - `output_max_bytes`: the maximum size in bytes of cell outputs; larger
* values may affect frontend performance
+ * - `serve_cached_sessions_in_apps`: if `True`, initialize applications with session cache.
+ * The default is `False`.
* - `std_stream_max_bytes`: the maximum size in bytes of console outputs;
* larger values may affect frontend performance
* - `pythonpath`: a list of directories to add to the Python search path.
@@ -5325,6 +5329,7 @@ export interface components {
output_max_bytes: number;
pythonpath?: string[];
reactive_tests: boolean;
+ serve_cached_sessions_in_apps?: boolean;
std_stream_max_bytes: number;
/** @enum {unknown} */
watcher_on_save: "autorun" | "lazy";
diff --git a/tests/_pyodide/test_pyodide_session.py b/tests/_pyodide/test_pyodide_session.py
index 177e7d05ee..7a43eaa452 100644
--- a/tests/_pyodide/test_pyodide_session.py
+++ b/tests/_pyodide/test_pyodide_session.py
@@ -351,7 +351,7 @@ async def test_pyodide_session_put_input(
# Notebook operations
(
'{"type": "create-notebook", "executionRequests": [{"cellId": "cell-1", "code": "print(1)", "type": "execute-cell"}], '
- '"setUiElementValueRequest": {"objectIds": [], "values": [], "type": "update-ui-element"}, '
+ '"cellIds": ["cell-1"], "setUiElementValueRequest": {"objectIds": [], "values": [], "type": "update-ui-element"}, '
'"autoRun": true}',
CreateNotebookCommand,
),
diff --git a/tests/_runtime/test_dotenv.py b/tests/_runtime/test_dotenv.py
index cf4bae0e3e..530713622f 100644
--- a/tests/_runtime/test_dotenv.py
+++ b/tests/_runtime/test_dotenv.py
@@ -84,6 +84,7 @@ async def test_load_dotenv_on_instantiate(mocked_kernel: MockedKernel):
# Create a CreationRequest
request = CreateNotebookCommand(
execution_requests=(),
+ cell_ids=(),
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
values=[],
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 7de42d438b..3c57e901e6 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -343,6 +343,7 @@ class TestExecution:
cell_id="1", code="s = mo.ui.slider(0, 10, value=1)"
),
),
+ cell_ids=("0", "1"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[(id_provider.take_id(), 2)]
),
@@ -360,6 +361,7 @@ class TestExecution:
er1 := ExecuteCellCommand(cell_id="1", code="y=x+1"),
er2 := ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
+ cell_ids=("0", "1", "2"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
@@ -395,6 +397,7 @@ class TestExecution:
ExecuteCellCommand(cell_id="1", code="y=x+1"),
ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
+ cell_ids=("0", "1", "2"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
@@ -422,6 +425,7 @@ class TestExecution:
er2 := ExecuteCellCommand(cell_id="1", code="y=x+1"),
er3 := ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
+ cell_ids=("0", "1", "2"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
@@ -450,6 +454,7 @@ class TestExecution:
ExecuteCellCommand(cell_id="1", code="y=x+1"),
ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
+ cell_ids=("0", "1", "2"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
@@ -492,6 +497,7 @@ class TestExecution:
ExecuteCellCommand(cell_id="1", code="y=x+1"),
ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
+ cell_ids=("0", "1", "2"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
@@ -520,6 +526,7 @@ class TestExecution:
er1 := ExecuteCellCommand(cell_id="1", code="y=x+1"),
er2 := ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
+ cell_ids=("0", "1", "2"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
@@ -555,6 +562,7 @@ class TestExecution:
ExecuteCellCommand(cell_id="2", code=" \n "),
ExecuteCellCommand(cell_id="3", code="y=x+1"),
),
+ cell_ids=("0", "1", "2", "3"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
@@ -1889,6 +1897,7 @@ except NameError:
ExecuteCellCommand(cell_id="1", code="y = 1"),
ExecuteCellCommand(cell_id="2", code="z = 2"),
),
+ cell_ids=("0", "1", "2"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
@@ -3693,6 +3702,7 @@ class TestMarkdownHandling:
# Create a creation request with auto_run=False to trigger the markdown handling
creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
+ cell_ids=tuple(cell.cell_id for cell in execution_requests),
auto_run=False,
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
@@ -3790,6 +3800,7 @@ class TestMarkdownHandling:
creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
+ cell_ids=tuple(cell.cell_id for cell in execution_requests),
auto_run=False,
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
@@ -3830,6 +3841,7 @@ class TestMarkdownHandling:
creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
+ cell_ids=tuple(cell.cell_id for cell in execution_requests),
auto_run=False,
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
@@ -3861,6 +3873,7 @@ class TestMarkdownHandling:
creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
+ cell_ids=tuple(cell.cell_id for cell in execution_requests),
auto_run=False,
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
@@ -3920,6 +3933,7 @@ class TestMarkdownHandling:
creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
+ cell_ids=tuple(cell.cell_id for cell in execution_requests),
auto_run=False,
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
@@ -3978,6 +3992,7 @@ class TestMarkdownHandling:
creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
+ cell_ids=tuple(cell.cell_id for cell in execution_requests),
auto_run=False,
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index 53ef297435..413c1e41d3 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -322,7 +322,7 @@ async def test_connects_to_existing_session_with_same_file(
# This can/may change if implementation changes, but this is a snapshot to
# make sure it doesn't change when we don't expect it to
assert len(messages1) == 14
- assert messages1[0]["op"] == "variables"
+ assert messages1[0]["op"] == "update-cell-ids"
# Connect second client - should connect to same session
with client.websocket_connect(ws_2) as websocket2:
@@ -339,7 +339,7 @@ async def test_connects_to_existing_session_with_same_file(
# This can/may change if implementation changes, but this is a snapshot to
# make sure it doesn't change when we don't expect it to
assert len(messages2) == 4
- assert messages2[0]["op"] == "variables"
+ assert messages2[0]["op"] == "update-cell-ids"
def flush_messages(
diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.py
index 9fa98f4549..0f6389039a 100644
--- a/tests/_server/test_sessions.py
+++ b/tests/_server/test_sessions.py
@@ -245,6 +245,7 @@ def test_kernel_manager_interrupt(tmp_path: Path) -> None:
),
),
),
+ cell_ids=("1",),
set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[], values=[]
),
@@ -1069,21 +1070,38 @@ def test_session_with_script_config_overrides(
@save_and_restore_main
-async def test_caching_enabled_only_in_edit_mode() -> None:
- """Test that caching is only enabled in EDIT mode, not RUN mode."""
- from marimo._session.extensions.extensions import CachingExtension
+async def test_caching_extension_respects_mode_and_config() -> None:
+ """Test caching enablement and mode across edit/run sessions."""
+ from marimo._session.extensions.extensions import (
+ CacheMode,
+ CachingExtension,
+ )
session_consumer = MagicMock()
session_consumer.connection_state.return_value = ConnectionState.OPEN
- def create_session(mode: SessionMode, auto_instantiate: bool) -> Session:
+ def create_session(
+ mode: SessionMode,
+ auto_instantiate: bool,
+ *,
+ serve_cached_sessions_in_apps: bool | None = None,
+ ) -> Session:
+ config_manager = get_default_config_manager(current_path=None)
+ if serve_cached_sessions_in_apps is not None:
+ config_manager = config_manager.with_overrides(
+ {
+ "runtime": {
+ "serve_cached_sessions_in_apps": serve_cached_sessions_in_apps
+ }
+ }
+ )
return SessionImpl.create(
initialization_id="test_session",
session_consumer=session_consumer,
mode=mode,
app_metadata=app_metadata,
app_file_manager=AppFileManager.from_app(InternalApp(App())),
- config_manager=get_default_config_manager(current_path=None),
+ config_manager=config_manager,
virtual_files_supported=True,
redirect_console_to_browser=False,
ttl_seconds=None,
@@ -1099,20 +1117,46 @@ async def test_caching_enabled_only_in_edit_mode() -> None:
assert len(extension) == 1
return extension[0]
- # Test 1: EDIT mode with auto_instantiate=False -> caching enabled
+ # Test 1: EDIT mode with auto_instantiate=False -> caching enabled/read-write
session_edit = create_session(SessionMode.EDIT, False)
# Find the CachingExtension
caching_extension_edit = find_caching_extension(session_edit)
assert caching_extension_edit.enabled is True
+ assert caching_extension_edit.mode is CacheMode.READ_WRITE
- # Test 2: RUN mode with auto_instantiate=True -> caching disabled
- session_run = create_session(SessionMode.RUN, True)
+ # Test 2: EDIT mode with auto_instantiate=True -> caching disabled
+ session_edit_disabled = create_session(SessionMode.EDIT, True)
+ caching_extension_edit_disabled = find_caching_extension(
+ session_edit_disabled
+ )
+ assert caching_extension_edit_disabled.enabled is False
+ assert caching_extension_edit_disabled.mode is CacheMode.READ_WRITE
+
+ # Test 3: RUN mode with config disabled -> caching disabled/read-only
+ session_run_disabled = create_session(
+ SessionMode.RUN, True, serve_cached_sessions_in_apps=False
+ )
# Find the CachingExtension
- caching_extension_run = find_caching_extension(session_run)
- assert caching_extension_run.enabled is False
+ caching_extension_run_disabled = find_caching_extension(
+ session_run_disabled
+ )
+ assert caching_extension_run_disabled.enabled is False
+ assert caching_extension_run_disabled.mode is CacheMode.READ
+
+ # Test 4: RUN mode with config enabled -> caching enabled/read-only
+ session_run_enabled = create_session(
+ SessionMode.RUN, True, serve_cached_sessions_in_apps=True
+ )
+ caching_extension_run_enabled = find_caching_extension(
+ session_run_enabled
+ )
+ assert caching_extension_run_enabled.enabled is True
+ assert caching_extension_run_enabled.mode is CacheMode.READ
# Cleanup
session_edit.close()
- session_run.close()
+ session_edit_disabled.close()
+ session_run_disabled.close()
+ session_run_enabled.close()
diff --git a/tests/_session/extensions/test_extensions.py b/tests/_session/extensions/test_extensions.py
index e264a405e2..f272bf1b40 100644
--- a/tests/_session/extensions/test_extensions.py
+++ b/tests/_session/extensions/test_extensions.py
@@ -10,6 +10,7 @@ import pytest
from marimo._session.events import SessionEventBus
from marimo._session.extensions.extensions import (
+ CacheMode,
CachingExtension,
HeartbeatExtension,
LoggingExtension,
@@ -106,6 +107,25 @@ class TestCachingExtension:
mock_cache.stop.assert_called_once()
+ @patch("marimo._session.extensions.extensions.SessionCacheManager")
+ def test_read_only_mode_skips_start(
+ self, mock_cache_cls, mock_session, event_bus
+ ) -> None:
+ """Test that read-only mode does not start the cache writer."""
+ mock_cache = Mock()
+ mock_cache_cls.return_value = mock_cache
+ mock_cache.read_session_view = Mock(
+ return_value=mock_session.session_view
+ )
+
+ extension = CachingExtension(enabled=True, mode=CacheMode.READ)
+ extension.on_attach(mock_session, event_bus)
+
+ mock_cache.start.assert_not_called()
+ mock_cache.read_session_view.assert_called_once()
+
+ extension.on_detach()
+
@patch("marimo._session.extensions.extensions.SessionCacheManager")
async def test_rename_updates_path(
self, mock_cache_cls, mock_session, event_bus
@@ -128,6 +148,28 @@ class TestCachingExtension:
mock_cache.rename_path.assert_called_once_with("/new/path.py")
extension.on_detach()
+ @patch("marimo._session.extensions.extensions.SessionCacheManager")
+ async def test_read_only_mode_ignores_rename(
+ self, mock_cache_cls, mock_session, event_bus
+ ) -> None:
+ """Test that read-only mode ignores rename events."""
+ mock_cache = Mock()
+ mock_cache_cls.return_value = mock_cache
+ mock_cache.read_session_view = Mock(
+ return_value=mock_session.session_view
+ )
+
+ extension = CachingExtension(enabled=True, mode=CacheMode.READ)
+ extension.on_attach(mock_session, event_bus)
+
+ mock_session.app_file_manager.path = "/new/path.py"
+ await extension.on_session_notebook_renamed(
+ mock_session, "/old/path.py"
+ )
+
+ mock_cache.rename_path.assert_not_called()
+ extension.on_detach()
+
class TestNotificationListenerExtension:
"""Tests for NotificationListenerExtension."""
diff --git a/tests/_session/state/test_session_view.py b/tests/_session/state/test_session_view.py
index e575a42bb8..b05edb5849 100644
--- a/tests/_session/state/test_session_view.py
+++ b/tests/_session/state/test_session_view.py
@@ -180,6 +180,7 @@ def test_ui_values(session_view: SessionView) -> None:
session_view.add_control_request(
CreateNotebookCommand(
execution_requests=(),
+ cell_ids=(),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[("test_ui3", 101112)]
),
@@ -441,6 +442,7 @@ def test_last_run_code(session_view: SessionView) -> None:
execution_requests=(
ExecuteCellCommand(cell_id=cell_id, code="print('hello')"),
),
+ cell_ids=(cell_id, "cell_2"),
set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),