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
Give notebooks a sink instead of a private stream (#11243)
Kiran Gadhaveb78538226737
diff --git a/marimo/_core/host.py b/marimo/_core/host.pyindex f58209acd0..e8434a47bb 100644--- a/marimo/_core/host.py+++ b/marimo/_core/host.py@@ -14,19 +14,38 @@ from marimo._core.backend import Backendfrom marimo._core.errors import NotFoundfrom marimo._core.notebook import Notebookfrom marimo._core.run_log import RetentionPolicy, RunLog-from marimo._core.stream import Event, Listener, Stream, message+from marimo._core.stream import Event, Listener, Sink, Stream, messageif TYPE_CHECKING:from collections.abc import Callable, Collection, Iterator, Sequence+ from contextlib import AbstractContextManager@dataclassclass _Entry:- """A notebook, the run history kept for it, and its subscription."""+ """A notebook and the run history kept for it."""notebook: Notebooklog: RunLog- unsubscribe: Callable[[], None]+++class _NotebookSink(Sink):+ """A notebook's sink: the run log sees each event, then the stream."""++ def __init__(self, stream: Stream, log: RunLog) -> None:+ self._stream = stream+ self._log = log++ def deferred(self) -> AbstractContextManager[None]:+ return self._stream.deferred()++ def _append(self, event: Event) -> Event:+ with self._stream.deferred():+ removals = self._log.observe(event)+ recorded = self._stream.append(event)+ for removed in removals:+ self._stream.append(removed)+ return recordedclass _NotebookRecords(Mapping[str, protocol.Notebook]):@@ -102,21 +121,12 @@ class Host:raise ValueError(f"project {record.project_id} is not in the catalog")- notebook = Notebook(record.id, backend)log = RunLog(lambda: self.clock())-- def publish(event: Event) -> None:- removals = log.observe(event)- self._stream.append(event)- for removal in removals:- self._stream.append(removal)-- self._records[record.id] = deepcopy(record)- self._entries[record.id] = _Entry(- notebook,- log,- notebook._stream.subscribe(publish, downstream=self._stream),+ notebook = Notebook(+ record.id, backend, _NotebookSink(self._stream, log))+ self._records[record.id] = deepcopy(record)+ self._entries[record.id] = _Entry(notebook, log)self._stream.publish(record, notebook_id=record.id, request_id=request_id)@@ -147,13 +157,10 @@ class Host:if entry is None:returnrecord = self._records.pop(notebook_id)- entry.notebook._dispose(request_id=request_id)-- def finish() -> None:- with self._stream.deferred():- for event in entry.log.clear():- self._stream.append(event)- entry.unsubscribe()+ with self._stream.deferred():+ entry.notebook._dispose(request_id=request_id)+ for event in entry.log.clear():+ self._stream.append(event)self._stream.remove("notebook",record.id,@@ -161,8 +168,6 @@ class Host:request_id=request_id,)- entry.notebook._stream.after_delivery(finish)-def notebook(self, notebook_id: str) -> Notebook:"""Return a notebook or raise `NotFound`."""entry = self._entries.get(notebook_id)diff --git a/marimo/_core/notebook.py b/marimo/_core/notebook.pyindex b8fa68e5df..82fad6444e 100644--- a/marimo/_core/notebook.py+++ b/marimo/_core/notebook.py@@ -12,37 +12,32 @@ from marimo._core import backend as be, protocolfrom marimo._core.errors import Conflict, NoRuntime, NotFoundfrom marimo._core.executions import Executions, Released, Removedfrom marimo._core.ids import mint-from marimo._core.stream import (- Event,- Kind,- Listener,- Stream,- kind_of,- message,- utcnow,-)+from marimo._core.stream import Event, Kind, kind_of, message, utcnowif TYPE_CHECKING:from collections.abc import Callable, Sequencefrom marimo._core.executions import Change- from marimo._core.stream import Body+ from marimo._core.stream import Body, Sinkclass Notebook:"""A notebook with execution results, a runtime, and client attachments.Commands call the backend. Backend reports update state and reach- subscribers through notebook events. Change execution state through- the notebook so each change reaches subscribers.+ the sink as notebook events. Change execution state through the+ notebook so each change reaches the sink."""def __init__(- self, notebook_id: protocol.NotebookId, backend: be.Backend+ self,+ notebook_id: protocol.NotebookId,+ backend: be.Backend,+ sink: Sink,) -> None:self._id = notebook_idself._backend = backend- self._stream = Stream(history=0)+ self._sink = sinkself._closed = Falseself._runtime: protocol.Runtime | None = Noneself._attachments: dict[str, protocol.Attachment] = {}@@ -51,10 +46,6 @@ class Notebook:# Correlate runtime events with the pending start, stop, or restart.self._runtime_request: str | None = None- def subscribe(self, listener: Listener) -> Callable[[], None]:- """Subscribe to future notebook events."""- return self._stream.subscribe(listener)-@propertydef executions(self) -> Executions:return self._executions@@ -78,7 +69,7 @@ class Notebook:self, *, request_id: str | None = None) -> tuple[protocol.Runtime, bool]:"""Return the runtime and whether this call started it."""- with self._stream.deferred():+ with self._sink.deferred():self._require_open()if self._runtime is not None:return self._runtime, False@@ -94,7 +85,7 @@ class Notebook:The runtime stays until the backend reports its exit. A failed runtimeis removed immediately."""- with self._stream.deferred():+ with self._sink.deferred():self._require_open()runtime = self._require_runtime()self._runtime_request = request_id@@ -114,7 +105,7 @@ class Notebook:The replacement starts after the old runtime exits."""- with self._stream.deferred():+ with self._sink.deferred():self._require_open()runtime = self._require_runtime()if runtime.status != "running":@@ -138,7 +129,7 @@ class Notebook:Calls `attach` with a new runtime ID before delivering events."""- with self._stream.deferred():+ with self._sink.deferred():self._require_open()if self._runtime is not None:if self._runtime.status != "failed":@@ -175,7 +166,7 @@ class Notebook:def run(self, code: str, *, request_id: str) -> protocol.Run:"""Queue scratch code on a running, idle runtime."""- with self._stream.deferred():+ with self._sink.deferred():self._require_open()runtime = self._require_runtime()if runtime.status != "running":@@ -282,7 +273,7 @@ class Notebook:if runtime.status == "terminating" and self._replacement is not None:replacement, self._replacement = self._replacement, Nonerequest_id = self._runtime_request- with self._stream.deferred():+ with self._sink.deferred():self._end_runtime()self._runtime_request = request_idself._set_runtime(replacement)@@ -370,7 +361,7 @@ class Notebook:self._remove("runtime", runtime.id, request_id)def _publish(self, body: Body, request_id: str | None) -> None:- self._stream.publish(+ self._sink.publish(body,notebook_id=self.id,request_id=request_id,@@ -382,7 +373,7 @@ class Notebook:object_id: str,request_id: str | None,) -> None:- self._stream.remove(+ self._sink.remove(kind,object_id,notebook_id=self.id,@@ -392,7 +383,7 @@ class Notebook:def _apply(self, changes: Sequence[Change]) -> None:"""Publish changes and release completed runs."""executions = self.executions- with self._stream.deferred():+ with self._sink.deferred():for change in changes:if isinstance(change, Released):executions.release(change.run_id)@@ -401,7 +392,7 @@ class Notebook:run_id = executions.run_id_of(change)request_id = executions.request_id(run_id)if isinstance(change, Removed):- self._stream.remove(+ self._sink.remove(change.kind,change.id,notebook_id=self.id,@@ -409,7 +400,7 @@ class Notebook:request_id=request_id,)else:- self._stream.publish(+ self._sink.publish(change,notebook_id=self.id,run_id=run_id,diff --git a/marimo/_core/stream.py b/marimo/_core/stream.pyindex 47e15a211d..ad7b02af6a 100644--- a/marimo/_core/stream.py+++ b/marimo/_core/stream.py@@ -8,9 +8,10 @@ stream from the last event id received on that stream.from __future__ import annotationsimport logging+from abc import ABC, abstractmethodfrom collections import dequefrom collections.abc import Callable, Collection, Iterator-from contextlib import ExitStack, contextmanager+from contextlib import AbstractContextManager, contextmanagerfrom copy import deepcopyfrom dataclasses import dataclassfrom datetime import datetime, timezone@@ -159,27 +160,13 @@ class Event:Listener = Callable[[Event], None]-class Stream:- """An ordered event log with bounded history and live subscriptions.+class Sink(ABC):+ """Where a producer publishes its events.- Callers serialize access on one thread. Published objects and returned- events are copied so readers cannot mutate the log or each other's data.+ A `Stream` is a sink. A host can give a notebook one that observes+ each event before the stream records it."""- def __init__(self, *, history: int = 1000) -> None:- self._last_id = 0- self._history: deque[Event] = deque(maxlen=history)- self._listeners: list[Listener] = []- self._downstream: list[Stream] = []- self._pending: deque[- tuple[Event, tuple[Listener, ...]] | Callable[[], None]- ] = deque()- self._dispatching = False-- @property- def last_id(self) -> int:- return self._last_id-def publish(self,body: Body,@@ -189,10 +176,9 @@ class Stream:run_id: protocol.RunId | None = None,) -> Event:"""Publish a new or updated object."""- kind = kind_of(body)data = message(body, request_id=request_id, time=utcnow())return self._append(- Event(kind, data, notebook_id=notebook_id, run_id=run_id)+ Event(kind_of(body), data, notebook_id=notebook_id, run_id=run_id))def remove(@@ -215,6 +201,33 @@ class Stream:))+ @abstractmethod+ def deferred(self) -> AbstractContextManager[None]:+ """Deliver events published in the block once it ends."""++ @abstractmethod+ def _append(self, event: Event) -> Event:+ """Record an event and return it as recorded."""+++class Stream(Sink):+ """An ordered event log with bounded history and live subscriptions.++ Callers serialize access on one thread. Published objects and returned+ events are copied so readers cannot mutate the log or each other's data.+ """++ def __init__(self, *, history: int = 1000) -> None:+ self._last_id = 0+ self._history: deque[Event] = deque(maxlen=history)+ self._listeners: list[Listener] = []+ self._pending: deque[tuple[Event, tuple[Listener, ...]]] = deque()+ self._dispatching = False++ @property+ def last_id(self) -> int:+ return self._last_id+def since(self, cursor: int) -> list[Event] | None:"""Return events after `cursor`, or `None` for a stale or future cursor."""if cursor == self._last_id:@@ -229,24 +242,17 @@ class Stream:[e for e in self._history if e.id is not None and e.id > cursor])- def subscribe(- self, listener: Listener, *, downstream: Stream | None = None- ) -> Callable[[], None]:+ def subscribe(self, listener: Listener) -> Callable[[], None]:"""Subscribe to future events and return an unsubscribe function.Subscriber exceptions are logged. Events published during delivery- follow the event being delivered. A downstream stream delivers- forwarded events after this stream drains.+ follow the event being delivered."""self._listeners.append(listener)- if downstream is not None:- self._downstream.append(downstream)def unsubscribe() -> None:if listener in self._listeners:self._listeners.remove(listener)- if downstream is not None:- self._downstream.remove(downstream)return unsubscribe@@ -286,29 +292,15 @@ class Stream:self._drain()return deepcopy(stamped)- def after_delivery(self, callback: Callable[[], None]) -> None:- """Call after queued events reach their listeners."""- if self._dispatching:- self._pending.append(callback)- else:- callback()-def _drain(self) -> None:- with ExitStack() as delivery:- for stream in self._downstream:- delivery.enter_context(stream.deferred())- self._dispatching = True- try:- while self._pending:- item = self._pending.popleft()- if callable(item):- item()- continue- pending, listeners = item- for listener in listeners:- try:- listener(deepcopy(pending))- except Exception:- LOGGER.exception("Error delivering host event")- finally:- self._dispatching = False+ self._dispatching = True+ try:+ while self._pending:+ pending, listeners = self._pending.popleft()+ for listener in listeners:+ try:+ listener(deepcopy(pending))+ except Exception:+ LOGGER.exception("Error delivering host event")+ finally:+ self._dispatching = Falsediff --git a/tests/_core/test_host.py b/tests/_core/test_host.pyindex ca469865e2..4633f4d8f0 100644--- a/tests/_core/test_host.py+++ b/tests/_core/test_host.py@@ -33,9 +33,8 @@ if TYPE_CHECKING:@pytest.mark.parametrize("trigger", ["runtime", "run"])[email protected]("source", ["host", "notebook"])def test_a_subscriber_can_remove_a_notebook_after_its_children(- host: Host, notebook: Notebook, trigger: str, source: str+ host: Host, notebook: Notebook, trigger: str) -> None:if trigger == "run":notebook.start()@@ -47,17 +46,7 @@ def test_a_subscriber_can_remove_a_notebook_after_its_children(if event.name == trigger:host.remove_notebook(notebook.id)- if source == "host":- host.subscribe(remove, notebook_id=notebook.id)- else:- host.subscribe(events.append, notebook_id=notebook.id)- notebook.subscribe(- lambda event: (- host.remove_notebook(notebook.id)- if event.name == trigger- else None- )- )+ host.subscribe(remove, notebook_id=notebook.id)if trigger == "run":notebook.run("1", request_id="request")assert names(events) == [