A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Fix matplotlib plots not rendering in HTML export (#5377)
Trevor Manz8517a0fdff5c
diff --git a/marimo/_schemas/generated/session.yaml b/marimo/_schemas/generated/session.yamlindex f78c7d0a2c..95c58b5f20 100644--- a/marimo/_schemas/generated/session.yaml+++ b/marimo/_schemas/generated/session.yaml@@ -8,7 +8,9 @@ components:type: stringconsole:items:- $ref: '#/components/schemas/StreamOutput'+ oneOf:+ - $ref: '#/components/schemas/StreamOutput'+ - $ref: '#/components/schemas/StreamMediaOutput'type: arrayid:type: string@@ -80,6 +82,47 @@ components:- metadata- cellstype: object+ StreamMediaOutput:+ properties:+ data:+ type: string+ mimetype:+ enum:+ - application/json+ - application/vnd.marimo+error+ - application/vnd.marimo+traceback+ - application/vnd.marimo+mimebundle+ - application/vnd.vega.v5+json+ - application/vnd.vegalite.v5+json+ - image/png+ - image/svg+xml+ - image/tiff+ - image/avif+ - image/bmp+ - image/gif+ - image/jpeg+ - video/mp4+ - video/mpeg+ - text/html+ - text/plain+ - text/markdown+ - text/latex+ - text/csv+ type: string+ name:+ enum:+ - media+ type: string+ type:+ enum:+ - stream+ type: string+ required:+ - type+ - name+ - data+ - mimetype+ type: objectStreamOutput:properties:name:diff --git a/marimo/_schemas/session.py b/marimo/_schemas/session.pyindex 033abdc20c..d61a3c6d16 100644--- a/marimo/_schemas/session.py+++ b/marimo/_schemas/session.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom typing import Any, Literal, Optional, Union+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._schemas.common import BaseDict# This file contains the schema for the notebook session.@@ -27,6 +28,13 @@ class StreamOutput(BaseDict):text: str+class StreamMediaOutput(BaseDict):+ type: Literal["stream"]+ name: Literal["media"]+ data: str+ mimetype: KnownMimeType++class ErrorOutput(BaseDict):type: Literal["error"]ename: str@@ -46,6 +54,11 @@ OutputType = Union[# Dict[str, Any], # For future output types, forwards-compatible]+ConsoleType = Union[+ StreamOutput,+ StreamMediaOutput,+]+class Cell(BaseDict):"""Code cell specific structure"""@@ -53,7 +66,7 @@ class Cell(BaseDict):id: strcode_hash: Optional[str]outputs: list[OutputType]- console: list[StreamOutput]+ console: list[ConsoleType]# We don't need to store code or cell config# since that exists in the notebook.py itselfdiff --git a/marimo/_server/session/serialize.py b/marimo/_server/session/serialize.pyindex e4bbd02b4d..c9d30bc840 100644--- a/marimo/_server/session/serialize.py+++ b/marimo/_server/session/serialize.py@@ -27,11 +27,13 @@ from marimo._schemas.notebook import (from marimo._schemas.session import (VERSION,Cell,+ ConsoleType,DataOutput,ErrorOutput,NotebookSessionMetadata,NotebookSessionV1,OutputType,+ StreamMediaOutput,StreamOutput,)from marimo._server.session.session_view import SessionView@@ -67,7 +69,7 @@ def serialize_session_view(view: SessionView) -> NotebookSessionV1:for cell_id, cell_op in view.cell_operations.items():outputs: list[OutputType] = []- console: list[StreamOutput] = []+ console: list[ConsoleType] = []# Convert outputif cell_op.output:@@ -90,7 +92,17 @@ def serialize_session_view(view: SessionView) -> NotebookSessionV1:# Convert console outputsfor console_out in as_list(cell_op.console):assert isinstance(console_out, CellOutput)- if console_out:+ if console_out.channel == CellChannel.MEDIA:+ console.append(+ StreamMediaOutput(+ type="stream",+ name="media",+ mimetype=console_out.mimetype,+ data=str(console_out.data),+ )+ )+ else:+ # catch all for everything elseconsole.append(StreamOutput(type="stream",@@ -172,15 +184,24 @@ def deserialize_session(session: NotebookSessionV1) -> SessionView:# Convert consoleconsole_outputs: list[CellOutput] = []for console in cell["console"]:- console_outputs.append(- CellOutput(- channel=CellChannel.STDERR- if console["name"] == "stderr"- else CellChannel.STDOUT,- data=console["text"],- mimetype="text/plain",+ if console["name"] == "media":+ console_outputs.append(+ CellOutput(+ channel=CellChannel.MEDIA,+ data=console["data"],+ mimetype=console["mimetype"],+ )+ )+ else:+ console_outputs.append(+ CellOutput(+ channel=CellChannel.STDERR+ if console["name"] == "stderr"+ else CellChannel.STDOUT,+ data=console["text"],+ mimetype="text/plain",+ ))- )cell_id = CellId_t(cell["id"])@@ -201,7 +222,9 @@ def serialize_notebook("""Convert a SessionView to a Notebook schema."""cells: list[NotebookCell] = []- for cell_id in view.cell_operations.keys():+ # Use document order from cell_manager instead of execution order from session_view+ # to ensure cells appear in the correct sequence in HTML export+ for cell_id in cell_manager.cell_ids():# Get the code from last_executed_code, fallback to empty stringcode = view.last_executed_code.get(cell_id, "")cell_data = cell_manager.get_cell_data(cell_id)diff --git a/openapi/src/session.ts b/openapi/src/session.tsindex 9f2b585353..d2259dc20b 100644--- a/openapi/src/session.ts+++ b/openapi/src/session.ts@@ -9,7 +9,10 @@ export interface components {schemas: {Cell: {code_hash: string | null;- console: components["schemas"]["StreamOutput"][];+ console: (+ | components["schemas"]["StreamOutput"]+ | components["schemas"]["StreamMediaOutput"]+ )[];id: string;outputs: (| components["schemas"]["ErrorOutput"]@@ -38,6 +41,35 @@ export interface components {metadata: components["schemas"]["NotebookSessionMetadata"];version: string;};+ StreamMediaOutput: {+ data: string;+ /** @enum {string} */+ mimetype:+ | "application/json"+ | "application/vnd.marimo+error"+ | "application/vnd.marimo+traceback"+ | "application/vnd.marimo+mimebundle"+ | "application/vnd.vega.v5+json"+ | "application/vnd.vegalite.v5+json"+ | "image/png"+ | "image/svg+xml"+ | "image/tiff"+ | "image/avif"+ | "image/bmp"+ | "image/gif"+ | "image/jpeg"+ | "video/mp4"+ | "video/mpeg"+ | "text/html"+ | "text/plain"+ | "text/markdown"+ | "text/latex"+ | "text/csv";+ /** @enum {string} */+ name: "media";+ /** @enum {string} */+ type: "stream";+ };StreamOutput: {/** @enum {string} */name: "stdout" | "stderr";diff --git a/scripts/generate_schemas.py b/scripts/generate_schemas.pyindex bb25311f93..32eea6ad14 100755--- a/scripts/generate_schemas.py+++ b/scripts/generate_schemas.py@@ -16,6 +16,7 @@ with app.setup:# Sessions.TimeMetadata,s.StreamOutput,+ s.StreamMediaOutput,s.ErrorOutput,s.DataOutput,s.Cell,diff --git a/tests/_server/session/test_serialize_session.py b/tests/_server/session/test_serialize_session.pyindex d033bfde12..f683851cc3 100644--- a/tests/_server/session/test_serialize_session.py+++ b/tests/_server/session/test_serialize_session.py@@ -6,6 +6,8 @@ import sysimport tempfilefrom pathlib import Path+import pytest+from marimo import __version__from marimo._ast.cell import CellConfigfrom marimo._ast.cell_manager import CellManager@@ -232,6 +234,75 @@ def test_serialize_notebook_multiple_cells():assert cell2["config"]["hide_code"] is True+def test_serialize_notebook_multiple_cells_not_top_down():+ """Test serializing an "out-of-order" notebook.++ Serialize a notebook in which the topological sort+ is different from the notebook order. Make sure+ the serialized notebook is in notebook order.+ """++ view = SessionView()+ cell_manager = CellManager()++ cell_id1 = CellId_t("cell1")+ cell_manager.register_cell(+ cell_id=cell_id1,+ code="print(x + 1)",+ name="output",+ config=CellConfig(column=1, hide_code=True),+ )++ cell_id2 = CellId_t("cell2")+ cell_manager.register_cell(+ cell_id=cell_id2,+ code="x = 2",+ name="setup",+ config=CellConfig(column=0, disabled=False),+ )++ view.cell_operations[cell_id2] = CellOp(+ cell_id=cell_id2,+ status="idle",+ output=None,+ console=[],+ timestamp=0,+ )+ view.last_executed_code[cell_id2] = "x = 1"++ # Add second cell to session view+ view.cell_operations[cell_id1] = CellOp(+ cell_id=cell_id1,+ status="idle",+ output=CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/plain",+ data="2",+ ),+ console=[],+ timestamp=0,+ )+ view.last_executed_code[cell_id1] = "print(x + 1)"++ result = serialize_notebook(view, cell_manager)++ assert len(result["cells"]) == 2++ cell1 = result["cells"][0]+ assert cell1["id"] == "cell1"+ assert cell1["code"] == "print(x + 1)"+ assert cell1["name"] == "output"+ assert cell1["config"]["column"] == 1+ assert cell1["config"]["hide_code"] is True++ cell2 = result["cells"][1]+ assert cell2["id"] == "cell2"+ assert cell2["code"] == "x = 1"+ assert cell2["name"] == "setup"+ assert cell2["config"]["column"] == 0+ assert cell2["config"]["disabled"] is False++def test_serialize_notebook_empty_code():"""Test serialization when cells have no executed code"""view = SessionView()@@ -282,6 +353,15 @@ def test_serialize_notebook_no_cells():assert len(result["cells"]) == 0+# TODO(akshayka): Reconcile this test with+# https://github.com/marimo-team/marimo/pull/5377. It appears we+# need to serialize notebook based on the cell manager not+# session view in order to get correct ordering of cells.+ reason="Unclear how to serialize a notebook when "+ "the cell manager's view of cells differs from the session view. "+ "The session view doesn't know the order of cells in the notebook."+)def test_serialize_notebook_missing_cell_data():"""Test serialization when cell exists in SessionView but not in CellManager"""view = SessionView()