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
Remove document mutation from `session.notify()` (#8886)
Trevor Manzb8638d2606a7
diff --git a/marimo/_server/api/endpoints/document.py b/marimo/_server/api/endpoints/document.pyindex 324e3452be..69f36307ac 100644--- a/marimo/_server/api/endpoints/document.py+++ b/marimo/_server/api/endpoints/document.py@@ -54,8 +54,9 @@ async def document_transaction(request: Request) -> BaseResponse:session_id = app_state.require_current_session_id()transaction = Transaction(changes=tuple(body.changes), source="frontend")+ applied = session.document.apply(transaction)session.notify(- NotebookDocumentTransactionNotification(transaction=transaction),+ NotebookDocumentTransactionNotification(transaction=applied),from_consumer_id=ConsumerId(session_id),)diff --git a/marimo/_session/extensions/extensions.py b/marimo/_session/extensions/extensions.pyindex 6cdba49ece..94c9f6c31a 100644--- a/marimo/_session/extensions/extensions.py+++ b/marimo/_session/extensions/extensions.py@@ -11,8 +11,15 @@ import asynciofrom enum import Enumfrom typing import TYPE_CHECKING, Optional+import msgspec+from marimo import _loggersfrom marimo._cli.print import red+from marimo._messaging.notification import (+ NotebookDocumentTransactionNotification,+ NotificationMessage,+)+from marimo._messaging.serde import try_deserialize_kernel_notification_namefrom marimo._messaging.types import KernelMessagefrom marimo._runtime import commandsfrom marimo._session.events import SessionEventListener@@ -226,6 +233,38 @@ class NotificationListenerExtension(SessionExtension):# Edit mode with original kernel manager uses connectionreturn ConnectionDistributor(kernel_manager.kernel_connection)+ @staticmethod+ def _on_kernel_message(session: Session, msg: KernelMessage) -> None:+ """Route a raw kernel message to the appropriate session method.++ Document transactions are intercepted and applied to the+ ``session.document``, then ``session.notify()`` is invoked with the (versioned) result.++ Everything else is forwarded verbatim via ``session.notify()``.++ TODO: if more notification types need server-side interception,+ consider a middleware chain instead of inline dispatch.+ """+ notif: KernelMessage | NotificationMessage = msg++ name = try_deserialize_kernel_notification_name(msg)+ if name == NotebookDocumentTransactionNotification.name:+ try:+ decoded = msgspec.json.decode(+ msg,+ type=NotebookDocumentTransactionNotification,+ )+ applied = session.document.apply(decoded.transaction)+ notif = NotebookDocumentTransactionNotification(+ transaction=applied+ )+ except Exception: # noqa: BLE001+ LOGGER.warning(+ "Failed to decode/apply kernel document transaction"+ )++ session.notify(notif, from_consumer_id=None)+def on_attach(self, session: Session, event_bus: SessionEventBus) -> None:del event_busself.distributor = self._create_distributor(@@ -233,7 +272,7 @@ class NotificationListenerExtension(SessionExtension):queue_manager=self.queue_manager,)self.distributor.add_consumer(- lambda msg: session.notify(msg, from_consumer_id=None)+ lambda msg: self._on_kernel_message(session, msg))self.distributor.start()diff --git a/marimo/_session/session.py b/marimo/_session/session.pyindex 04db26cccb..432a5a047f 100644--- a/marimo/_session/session.py+++ b/marimo/_session/session.py@@ -12,20 +12,14 @@ import contextlibfrom typing import TYPE_CHECKING, Optionalfrom uuid import uuid4-import msgspec-from marimo import _loggersfrom marimo._cli.sandbox import SandboxModefrom marimo._config.manager import MarimoConfigManager, ScriptConfigManagerfrom marimo._messaging.notebook.document import NotebookCell, NotebookDocumentfrom marimo._messaging.notification import (- NotebookDocumentTransactionNotification,NotificationMessage,)-from marimo._messaging.serde import (- serialize_kernel_message,- try_deserialize_kernel_notification_name,-)+from marimo._messaging.serde import serialize_kernel_messagefrom marimo._messaging.types import KernelMessagefrom marimo._runtime import commandsfrom marimo._runtime.commands import (@@ -421,26 +415,7 @@ class SessionImpl(Session):operation: NotificationMessage | KernelMessage,from_consumer_id: Optional[ConsumerId],) -> None:- """Write an operation to the session consumer and the session view."""- # Intercept document transactions: apply to session.document- # (stamps version), then re-serialize for broadcast.- # Kernel notifications arrive as bytes via the stream distributor;- # server-side callers (e.g. file-watch) pass typed objects.- if isinstance(operation, bytes):- name = try_deserialize_kernel_notification_name(operation)- if name == NotebookDocumentTransactionNotification.name:- try:- operation = self._apply_document_transaction(- msgspec.json.decode(- operation,- type=NotebookDocumentTransactionNotification,- )- )- except Exception:- LOGGER.warning("Failed to decode document transaction")- elif isinstance(operation, NotebookDocumentTransactionNotification):- operation = self._apply_document_transaction(operation)-+ """Broadcast a notification to session consumers."""if isinstance(operation, bytes):notification = operationelse:@@ -449,18 +424,6 @@ class SessionImpl(Session):self.room.broadcast(notification, except_consumer=from_consumer_id)self._event_bus.emit_notification_sent(self, notification)- def _apply_document_transaction(- self,- notif: NotebookDocumentTransactionNotification,- ) -> NotebookDocumentTransactionNotification:- """Apply to session.document, return with version stamped."""- try:- applied = self.document.apply(notif.transaction)- return NotebookDocumentTransactionNotification(transaction=applied)- except (ValueError, KeyError):- LOGGER.warning("Failed to apply document transaction")- return notif-def close(self) -> None:"""Close the session.diff --git a/marimo/_session/types.py b/marimo/_session/types.pyindex 3fbd0076ec..6954ebac1c 100644--- a/marimo/_session/types.py+++ b/marimo/_session/types.py@@ -175,7 +175,7 @@ class Session(Protocol):operation: NotificationMessage | KernelMessage,from_consumer_id: Optional[ConsumerId],) -> None:- """Write an operation to the session consumer and the session view."""+ """Broadcast a notification to session consumers."""...def instantiate(