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.

improve: cached session invalidation (#4284)

Akshay Agrawal0584fbb3fde6
diff --git a/marimo/_server/session/serialize.py b/marimo/_server/session/serialize.py
index 7a0901cdc4..18b66cabf1 100644
--- a/marimo/_server/session/serialize.py
+++ b/marimo/_server/session/serialize.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import hashlib
import json
+from dataclasses import dataclass
from pathlib import Path
from typing import Any, Optional, Union, cast
@@ -240,6 +241,12 @@ class SessionCacheWriter(AsyncBackgroundTask):
break
+@dataclass
+class SessionCacheKey:
+ codes: tuple[str | None, ...]
+ marimo_version: str
+
+
class SessionCacheManager:
"""Manages the session cache writer.
@@ -285,13 +292,38 @@ class SessionCacheManager:
self.path = new_path
self.start()
- def read_session_view(self) -> SessionView:
- """Read the session view from the cache file"""
+ def is_cache_hit(
+ self, notebook_session: NotebookSessionV1, key: SessionCacheKey
+ ) -> bool:
+ if (len(key.codes) != len(notebook_session["cells"])) or any(
+ _hash_code(code) != cell["code_hash"]
+ for code, cell in zip(key.codes, notebook_session["cells"])
+ ):
+ return False
+ if (
+ key.marimo_version
+ != notebook_session["metadata"]["marimo_version"]
+ ):
+ return False
+ return True
+
+ def read_session_view(self, key: SessionCacheKey) -> SessionView:
+ """Read the session view from the cache files.
+
+ Mutates the session view on cache hit.
+ """
if self.path is None:
return self.session_view
cache_file = get_session_cache_file(Path(self.path))
if not cache_file.exists():
return self.session_view
+ notebook_session: NotebookSessionV1 = json.loads(
+ cache_file.read_text()
+ )
+ if not self.is_cache_hit(notebook_session, key):
+ LOGGER.debug("Session view cache miss")
+ return self.session_view
+
self.session_view = deserialize_session(
json.loads(cache_file.read_text())
)
diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.py
index 6f1f99b93c..40ec829ac0 100644
--- a/marimo/_server/sessions.py
+++ b/marimo/_server/sessions.py
@@ -65,6 +65,7 @@ from marimo._server.model import ConnectionState, SessionConsumer, SessionMode
from marimo._server.models.models import InstantiateRequest
from marimo._server.recents import RecentFilesManager
from marimo._server.session.serialize import (
+ SessionCacheKey,
SessionCacheManager,
)
from marimo._server.session.session_view import SessionView
@@ -705,13 +706,21 @@ class Session:
Overwrites the existing session view.
Mutates the existing session.
"""
+ from marimo import __version__
+
LOGGER.debug("Syncing session view from cache")
self.session_cache_manager = SessionCacheManager(
session_view=self.session_view,
path=self.app_file_manager.path,
interval=self.SESSION_CACHE_INTERVAL_SECONDS,
)
- self.session_view = self.session_cache_manager.read_session_view()
+
+ app = self.app_file_manager.app
+ codes = tuple(
+ cell_data.code for cell_data in app.cell_manager.cell_data()
+ )
+ key = SessionCacheKey(codes=codes, marimo_version=__version__)
+ self.session_view = self.session_cache_manager.read_session_view(key)
self.session_cache_manager.start()
def __repr__(self) -> str:
diff --git a/tests/_server/session/test_serialize_session.py b/tests/_server/session/test_serialize_session.py
index bd272ca735..628d1d5cfa 100644
--- a/tests/_server/session/test_serialize_session.py
+++ b/tests/_server/session/test_serialize_session.py
@@ -6,11 +6,14 @@ import sys
import tempfile
from pathlib import Path
+from marimo import __version__
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.errors import MarimoExceptionRaisedError, UnknownError
from marimo._messaging.ops import CellOp
+from marimo._runtime.requests import ExecuteMultipleRequest
from marimo._schemas.session import NotebookSessionV1
from marimo._server.session.serialize import (
+ SessionCacheKey,
SessionCacheManager,
SessionCacheWriter,
_hash_code,
@@ -408,7 +411,12 @@ class TestSessionCacheManager:
"""Test reading session view without path"""
view = SessionView()
manager = SessionCacheManager(view, None, 0.1)
- assert manager.read_session_view() == view
+ assert (
+ manager.read_session_view(
+ SessionCacheKey(codes=tuple(), marimo_version="-1")
+ )
+ == view
+ )
def test_read_session_view_no_cache(self):
"""Test reading session view with no cache file"""
@@ -416,7 +424,12 @@ class TestSessionCacheManager:
with tempfile.TemporaryDirectory() as tmpdir:
path = Path(tmpdir) / "notebook.py"
manager = SessionCacheManager(view, path, 0.1)
- assert manager.read_session_view() == view
+ assert (
+ manager.read_session_view(
+ SessionCacheKey(codes=tuple(), marimo_version="-1")
+ )
+ == view
+ )
async def test_read_session_view_with_cache(self):
"""Test reading session view from cache file"""
@@ -444,8 +457,129 @@ class TestSessionCacheManager:
# Read back
manager = SessionCacheManager(SessionView(), path, 0.1)
- loaded_view = manager.read_session_view()
+ loaded_view = manager.read_session_view(
+ SessionCacheKey(codes=(None,), marimo_version=__version__)
+ )
assert "cell1" in loaded_view.cell_operations
cell = loaded_view.cell_operations["cell1"]
assert cell.output is not None
assert cell.output.data == "test data"
+
+ async def test_read_session_view_cache_miss_code(self):
+ """Test reading session view from cache file"""
+ view = SessionView()
+ view.cell_operations["cell1"] = CellOp(
+ cell_id="cell1",
+ status="idle",
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/plain",
+ data="test data",
+ ),
+ console=[],
+ timestamp=0,
+ )
+ view.add_control_request(
+ ExecuteMultipleRequest(cell_ids=["cell1"], codes=["a"])
+ )
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ path = Path(tmpdir) / "notebook.py"
+ cache_file = get_session_cache_file(path)
+ cache_file.parent.mkdir(parents=True)
+
+ # Write cache file
+ data = serialize_session_view(view)
+ cache_file.write_text(json.dumps(data))
+
+ # Read back
+ manager = SessionCacheManager(SessionView(), path, 0.1)
+ loaded_view = manager.read_session_view(
+ # foo != a, cache miss
+ SessionCacheKey(codes=("foo",), marimo_version=__version__)
+ )
+ assert not loaded_view.cell_operations
+
+ async def test_read_session_view_cache_miss_version(self):
+ """Test reading session view from cache file"""
+ view = SessionView()
+ view.add_control_request(
+ ExecuteMultipleRequest(cell_ids=["1", "2"], codes=["a", "b"])
+ )
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ path = Path(tmpdir) / "notebook.py"
+ cache_file = get_session_cache_file(path)
+ cache_file.parent.mkdir(parents=True)
+
+ # Write cache file
+ data = serialize_session_view(view)
+ cache_file.write_text(json.dumps(data))
+
+ # Read back
+ manager = SessionCacheManager(SessionView(), path, 0.1)
+ loaded_view = manager.read_session_view(
+ SessionCacheKey(
+ codes=(
+ "a",
+ "b",
+ ),
+ marimo_version="-1",
+ )
+ )
+ assert not loaded_view.cell_operations
+
+ async def test_read_session_view_cache_hit(self):
+ """Test reading session view from cache file"""
+ view = SessionView()
+ view.cell_operations["cell1"] = CellOp(
+ cell_id="cell1",
+ status="idle",
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/plain",
+ data="test data",
+ ),
+ console=[],
+ timestamp=0,
+ )
+ view.cell_operations["cell2"] = CellOp(
+ cell_id="cell2",
+ status="idle",
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/plain",
+ data="test data",
+ ),
+ console=[],
+ timestamp=0,
+ )
+
+ view.add_control_request(
+ ExecuteMultipleRequest(
+ cell_ids=["cell1", "cell2"], codes=["a", "b"]
+ )
+ )
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ path = Path(tmpdir) / "notebook.py"
+ cache_file = get_session_cache_file(path)
+ cache_file.parent.mkdir(parents=True)
+
+ # Write cache file
+ data = serialize_session_view(view)
+ cache_file.write_text(json.dumps(data))
+
+ # Read back
+ manager = SessionCacheManager(SessionView(), path, 0.1)
+ loaded_view = manager.read_session_view(
+ SessionCacheKey(
+ codes=(
+ "a",
+ "b",
+ ),
+ marimo_version=__version__,
+ )
+ )
+ # cache hit: codes and version match
+ assert len(loaded_view.cell_operations) == 2
diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.py
index a13cace844..c2fe4377e1 100644
--- a/tests/_server/test_sessions.py
+++ b/tests/_server/test_sessions.py
@@ -967,6 +967,10 @@ def __():
)
app_file_manager = AppFileManager(filename=str(notebook_path))
+ codes = tuple(
+ cell_data.code
+ for cell_data in app_file_manager.app.cell_manager.cell_data()
+ )
session = Session(
session_id,
session_consumer,