Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions marimo/_pyodide/pyodide_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,11 @@
if TYPE_CHECKING:
from collections.abc import Callable

from marimo._ast.cell import CellConfig
from marimo._ast.cell_manager import CellManager
from marimo._messaging.types import KernelMessage
from marimo._pyodide.notebook import PyodideNotebook
from marimo._runtime.context.types import RuntimeContext
from marimo._session.notebook.file_manager import AppFileManager
from marimo._types.ids import CellId_t

LOGGER = _loggers.marimo_logger()

Expand Down Expand Up @@ -180,7 +179,7 @@ async def start(self) -> None:
input_queue=self._queue_manager.input_queue,
on_message=self._on_message,
session_mode=self.mode,
configs=self.app_manager.app.cell_manager.config_map(),
cell_manager=self.app_manager.app.cell_manager,
app_metadata=self.app_metadata,
user_config=self._initial_user_config,
)
Expand Down Expand Up @@ -602,7 +601,7 @@ def _launch_pyodide_kernel(
input_queue: asyncio.Queue[InputReply],
on_message: Callable[[KernelMessage], None],
session_mode: SessionMode,
configs: dict[CellId_t, CellConfig],
cell_manager: CellManager,
app_metadata: AppMetadata,
user_config: MarimoConfig,
) -> RestartableTask:
Expand Down Expand Up @@ -643,7 +642,7 @@ def _launch_pyodide_kernel(
stream=stream, stdout=stdout, stderr=stderr, stdin=stdin
),
debugger=debugger,
configs=configs,
configs=cell_manager.config_map(),
app_metadata=app_metadata,
user_config=user_config,
mode=session_mode,
Expand All @@ -653,6 +652,10 @@ def _launch_pyodide_kernel(
)
)

kernel.seed_startup_cells(
cell._cell for cell in cell_manager.cells() if cell is not None
)

if is_edit_mode:
signal.signal(signal.SIGINT, handlers.construct_interrupt_handler())

Expand Down
23 changes: 16 additions & 7 deletions marimo/_runtime/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -987,6 +987,21 @@ def _register_cell(
LOGGER.debug("parents: %s", self.graph.parents[cell_id])
LOGGER.debug("children: %s", self.graph.children[cell_id])

def _compile_filename(self) -> str | None:
# In run mode or debugpy, tracebacks reference the real notebook.
if get_mode() == "run" or os.environ.get("DEBUGPY_RUNNING"):
return self.app_metadata.filename
return None

def seed_startup_cells(self, cells: Iterable[CellImpl]) -> None:
"""Reuse cells compiled by the in-process notebook loader."""
if self._compile_filename() is not None:
return
for cell in cells:
self._startup_cell_cache.store(
cell.cell_id, cell.code, cell.as_compiled(), None
)

def _try_compiling_cell(
self, cell_id: CellId_t, code: str, carried_imports: list[ImportData]
) -> tuple[CellImpl | None, Error | None]:
Expand All @@ -996,17 +1011,11 @@ def _try_compiling_cell(

error: Error | None = None
try:
# In run mode or debugpy, pass the notebook filename so
# tracebacks reference the real file instead of synthetic
# cell files.
filename = None
if get_mode() == "run" or os.environ.get("DEBUGPY_RUNNING"):
filename = self.app_metadata.filename
cell = compile_cell(
code,
cell_id=cell_id,
carried_imports=carried_imports,
filename=filename,
filename=self._compile_filename(),
)
except Exception as e:
cell = None
Expand Down
39 changes: 25 additions & 14 deletions tests/_pyodide/test_pyodide_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,13 @@
import pytest

from marimo._ast.app_config import _AppConfig
from marimo._ast.cell_manager import CellManager
from marimo._ast.compiler import compile_cell
from marimo._config.config import DEFAULT_CONFIG, merge_config
from marimo._config.config_schema import FileBrowserConfig
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.input import InputReply
from marimo._messaging.serde import deserialize_kernel_notification_name
from marimo._messaging.types import KernelMessage
from marimo._pyodide.pyodide_session import (
AsyncQueueManager,
Expand Down Expand Up @@ -158,21 +161,29 @@ async def test_async_queue_manager() -> None:
)


async def test_pyodide_session_start(
async def test_pyodide_session_start_reuses_loaded_cells(
pyodide_session: PyodideSession,
mock_pyodide_http: MagicMock,
) -> None:
# Test starting the session
start_task = asyncio.create_task(pyodide_session.start())
await asyncio.sleep(0) # Let the task start
assert pyodide_session.kernel_task is not None
mock_pyodide_http.patch_all.assert_called_once()
pyodide_session.kernel_task.stop()
start_task.cancel()
try:
await start_task
except asyncio.CancelledError:
pass
completed = asyncio.Event()

def on_message(message: KernelMessage) -> None:
if deserialize_kernel_notification_name(message) == "completed-run":
completed.set()

pyodide_session.consumers.append(on_message)
pyodide_session.instantiate(auto_run=True)
with patch(
"marimo._runtime.runtime.compile_cell", wraps=compile_cell
) as kernel_compile:
task = asyncio.create_task(pyodide_session.start())
try:
await asyncio.wait_for(completed.wait(), timeout=10)
mock_pyodide_http.patch_all.assert_called_once()
kernel_compile.assert_not_called()
finally:
pyodide_session.kernel_task.stop()
await task


async def test_pyodide_kernel_teardown_runs_on_stop(
Expand Down Expand Up @@ -246,7 +257,7 @@ async def shutdown_wasm_runtime_work(*_args: Any, **_kwargs: Any) -> None:
input_queue=asyncio.Queue(),
on_message=lambda _msg: None,
session_mode=SessionMode.EDIT,
configs={},
cell_manager=CellManager(),
app_metadata=AppMetadata(
query_params={},
cli_args={},
Expand Down Expand Up @@ -325,7 +336,7 @@ async def shutdown_wasm_runtime_work(*_args: Any, **_kwargs: Any) -> None:
input_queue=asyncio.Queue(),
on_message=lambda _msg: None,
session_mode=SessionMode.EDIT,
configs={},
cell_manager=CellManager(),
app_metadata=AppMetadata(
query_params={},
cli_args={},
Expand Down
Loading