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.

Specify how clients derive outdated results (#11444)

Trevor Manzbac0b373a022
diff --git a/protocols/host/spec.md b/protocols/host/spec.md
index 34c0d2fb49..90b505ba07 100644
--- a/protocols/host/spec.md
+++ b/protocols/host/spec.md
@@ -195,12 +195,16 @@ A completed cell execution is **current** when:
- each name it depends on that was unbound is still unbound,
- the execution that bound each of those variables is current.
-A client finds a variable by the recorded revision's `execution` and the name.
-If none exists, that execution was replaced or removed. If its `update` is
-higher, the value was updated. If that execution's `code_hash` differs from
-its cell's, the cell was edited. The first that applies is why the result is
-**outdated**. A cell with no execution has no result to compare. Scratch
-executions have no cell and are not compared.
+A client looks up each dependency by name, and also by the recorded revision's
+`execution` unless it is null. A dependency was replaced if no variable matches
+its revision, or if a variable now has a name recorded as null. It was updated
+if the variable's `update` is higher. An execution was edited if its
+`code_hash` differs from its cell's. A result whose dependency was bound by an
+outdated execution is outdated for the same reason. The first of replaced,
+updated, and edited that applies is why the result is **outdated**.
+
+A cell without an execution has no result to compare. Scratch executions run in
+a local namespace, bind no variables, and are not compared.
For example, cell `k7f2` reads `x`, which cell `c3` binds:
diff --git a/tests/_server/host/live.py b/tests/_server/host/live.py
new file mode 100644
index 0000000000..56e54e81a5
--- /dev/null
+++ b/tests/_server/host/live.py
@@ -0,0 +1,93 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""A host serving one notebook from a real session and kernel."""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+from typing import TYPE_CHECKING
+
+from marimo._config.config import DEFAULT_CONFIG
+from marimo._server.host.bridge import SessionBridge
+from marimo._server.host.context import HostContext
+from marimo._server.main import create_starlette_app
+from marimo._server.workspace import SingleFileWorkspace
+from marimo._utils.marimo_path import MarimoPath
+from tests._server.host.drive import PORT, finished, request, wait_for
+from tests._server.mocks import (
+ get_mock_session_manager,
+ get_starlette_server_state_init,
+)
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator
+ from pathlib import Path
+
+ from starlette.applications import Starlette
+
+ from marimo._config.config import OnCellChangeType
+ from tests._server.host.drive import Response
+
+TOKEN = "execution-test"
+AUTH = {"Authorization": f"Bearer {TOKEN}"}
+
+
+def key(value: str) -> dict[str, str]:
+ return {**AUTH, "Idempotency-Key": value}
+
+
+async def open_host(
+ tmp_path: Path,
+ source: str,
+ *,
+ on_cell_change: OnCellChangeType = "autorun",
+) -> AsyncIterator[tuple[Starlette, str, Response]]:
+ """Serve `source` with a started runtime, following its events."""
+ manager = get_mock_session_manager()
+ file = tmp_path / "notebook.py"
+ file.write_text(source)
+ manager.workspace = SingleFileWorkspace.from_path(MarimoPath(file))
+ manager.redirect_console_to_browser = True
+ manager._config_manager = manager._config_manager.with_overrides(
+ {
+ "runtime": {
+ **DEFAULT_CONFIG["runtime"],
+ "on_cell_change": on_cell_change,
+ }
+ }
+ )
+ async with contextlib.AsyncExitStack() as cleanup:
+ cleanup.push_async_callback(manager.shutdown)
+ app = create_starlette_app(base_url="", enable_auth=True)
+ get_starlette_server_state_init(session_manager=manager).apply(
+ app.state
+ )
+ bridge = SessionBridge(manager)
+ cleanup.callback(bridge.close)
+ await bridge.open()
+ app.state.host_context = HostContext(
+ bridge=bridge, token=TOKEN, port=PORT
+ )
+ notebook = next(iter(bridge.host.notebooks.values()))
+ events, task, disconnect = request(
+ app, "GET", f"/notebooks/{notebook.id}/events", headers=AUTH
+ )
+ cleanup.push_async_callback(asyncio.wait_for, task, 5)
+ cleanup.callback(disconnect)
+ started = await finished(
+ app,
+ "PUT",
+ f"/notebooks/{notebook.id}/runtime",
+ headers=key("start"),
+ )
+ assert started.status == 202
+ await wait_for(
+ events,
+ lambda response: any(
+ r.get("data", {}).get("runtime", {}).get("status") == "running"
+ for r in response.records
+ ),
+ timeout=15,
+ )
+ yield app, notebook.id, events
diff --git a/tests/_server/host/staleness.py b/tests/_server/host/staleness.py
new file mode 100644
index 0000000000..d8b5deca52
--- /dev/null
+++ b/tests/_server/host/staleness.py
@@ -0,0 +1,134 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""A client's derivation of which results are current, as the spec states it.
+
+See "Runs and results" in `protocols/host/spec.md`.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Literal
+
+import msgspec
+
+from marimo._core import protocol
+from tests._server.host.drive import request, wait_for
+from tests._server.host.live import AUTH
+
+if TYPE_CHECKING:
+ from typing import Any
+
+ from starlette.applications import Starlette
+
+Outdated = Literal["replaced", "updated", "edited"]
+"""Why a result is outdated. When several apply, the first listed wins."""
+
+_ORDER: tuple[Outdated, ...] = ("replaced", "updated", "edited")
+
+
+@dataclass(frozen=True)
+class Snapshot:
+ """The cells, executions, and variables a client holds."""
+
+ cells: dict[str, protocol.Cell]
+ executions: dict[str, protocol.Execution]
+ variables: tuple[protocol.Variable, ...]
+
+ @classmethod
+ def decode(cls, records: list[dict[str, Any]]) -> Snapshot:
+ cells: dict[str, protocol.Cell] = {}
+ executions: dict[str, protocol.Execution] = {}
+ variables: list[protocol.Variable] = []
+ for record in records:
+ event = record.get("event")
+ raw = msgspec.json.encode(record.get("data"))
+ if event == "cell":
+ cell = msgspec.json.decode(raw, type=protocol.CellMessage).cell
+ cells[cell.id] = cell
+ elif event == "execution":
+ execution = msgspec.json.decode(
+ raw, type=protocol.ExecutionMessage
+ ).execution
+ executions[execution.id] = execution
+ elif event == "variable":
+ variables.append(
+ msgspec.json.decode(
+ raw, type=protocol.VariableMessage
+ ).variable
+ )
+ return cls(cells, executions, tuple(variables))
+
+ def latest(self, cell_id: str) -> protocol.Execution | None:
+ """The cell's completed execution, if it has one."""
+ return next(
+ (
+ execution
+ for execution in self.executions.values()
+ if execution.cell_id == cell_id
+ and execution.status == "completed"
+ ),
+ None,
+ )
+
+ def outdated(self) -> dict[str, Outdated]:
+ """Why each outdated cell's result is outdated, by cell id.
+
+ Cells whose result is current, or that have no result to compare,
+ are omitted.
+ """
+ reasons: dict[str, Outdated] = {}
+ for cell_id in self.cells:
+ execution = self.latest(cell_id)
+ reason = None if execution is None else self._reason(execution)
+ if reason is not None:
+ reasons[cell_id] = reason
+ return reasons
+
+ def _reason(self, execution: protocol.Execution) -> Outdated | None:
+ assert execution.cell_id is not None
+ reasons = [
+ reason
+ for name, revision in execution.depends_on.items()
+ if (reason := self._dependency(name, revision)) is not None
+ ]
+ if execution.code_hash != self.cells[execution.cell_id].code_hash:
+ reasons.append("edited")
+ return min(reasons, key=_ORDER.index, default=None)
+
+ def _dependency(
+ self, name: str, revision: protocol.Revision | None
+ ) -> Outdated | None:
+ if revision is None:
+ bound = any(v.name == name for v in self.variables)
+ return "replaced" if bound else None
+ variable = next(
+ (
+ v
+ for v in self.variables
+ if v.name == name
+ and v.revision.execution == revision.execution
+ ),
+ None,
+ )
+ if variable is None:
+ return "replaced"
+ if variable.revision.update != revision.update:
+ return "updated"
+ return self._reason(self.executions[variable.execution_id])
+
+
+async def snapshot(app: Starlette, notebook_id: str) -> Snapshot:
+ """Connect as a new client and read the notebook's state."""
+ response, task, disconnect = request(
+ app, "GET", f"/notebooks/{notebook_id}/events", headers=AUTH
+ )
+ try:
+ await wait_for(response, lambda r: "ready" in r.names())
+ finally:
+ disconnect()
+ await asyncio.wait_for(task, 5)
+ ready = response.names().index("ready")
+ return Snapshot.decode(
+ [r for r in response.records if "event" in r][:ready]
+ )
diff --git a/tests/_server/host/test_host_execution.py b/tests/_server/host/test_host_execution.py
index 03e420e45a..03f1ea6101 100644
--- a/tests/_server/host/test_host_execution.py
+++ b/tests/_server/host/test_host_execution.py
@@ -3,25 +3,16 @@
from __future__ import annotations
-import asyncio
import json
from typing import TYPE_CHECKING
import pytest
from marimo._core.document import code_hash
-from marimo._server.host.bridge import SessionBridge
-from marimo._server.host.context import HostContext
-from marimo._server.main import create_starlette_app
-from marimo._server.workspace import SingleFileWorkspace
from marimo._session.notebook import AppFileManager
from marimo._session.requests import InstantiateNotebookRequest
-from marimo._utils.marimo_path import MarimoPath
-from tests._server.host.drive import PORT, finished, request, wait_for
-from tests._server.mocks import (
- get_mock_session_manager,
- get_starlette_server_state_init,
-)
+from tests._server.host.drive import finished, wait_for
+from tests._server.host.live import key, open_host
if TYPE_CHECKING:
from collections.abc import AsyncIterator
@@ -31,12 +22,6 @@ if TYPE_CHECKING:
from tests._server.host.drive import Response
-AUTH = {"Authorization": "Bearer execution-test"}
-
-
-def key(value: str) -> dict[str, str]:
- return {**AUTH, "Idempotency-Key": value}
-
@pytest.fixture
def notebook_source(request: pytest.FixtureRequest) -> str:
@@ -55,44 +40,8 @@ async def live_host(
tmp_path: Path,
notebook_source: str,
) -> AsyncIterator[tuple[Starlette, str, Response]]:
- manager = get_mock_session_manager()
- file = tmp_path / "notebook.py"
- file.write_text(notebook_source)
- manager.workspace = SingleFileWorkspace.from_path(MarimoPath(file))
- manager.redirect_console_to_browser = True
- app = create_starlette_app(base_url="", enable_auth=True)
- get_starlette_server_state_init(session_manager=manager).apply(app.state)
- bridge = SessionBridge(manager)
- await bridge.open()
- app.state.host_context = HostContext(
- bridge=bridge, token="execution-test", port=PORT
- )
- notebook = next(iter(bridge.host.notebooks.values()))
- events, task, disconnect = request(
- app, "GET", f"/notebooks/{notebook.id}/events", headers=AUTH
- )
- try:
- started = await finished(
- app,
- "PUT",
- f"/notebooks/{notebook.id}/runtime",
- headers=key("start"),
- )
- assert started.status == 202
- await wait_for(
- events,
- lambda response: any(
- r.get("data", {}).get("runtime", {}).get("status") == "running"
- for r in response.records
- ),
- timeout=15,
- )
- yield app, notebook.id, events
- finally:
- disconnect()
- await asyncio.wait_for(task, 5)
- bridge.close()
- await manager.shutdown()
+ async with open_host(tmp_path, notebook_source) as host:
+ yield host
async def test_move_preserves_the_running_notebook(
diff --git a/tests/_server/host/test_host_staleness.py b/tests/_server/host/test_host_staleness.py
new file mode 100644
index 0000000000..f8350f1a58
--- /dev/null
+++ b/tests/_server/host/test_host_staleness.py
@@ -0,0 +1,243 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Clients derive whether results are current from a real host's stream."""
+
+from __future__ import annotations
+
+import contextlib
+import itertools
+import json
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any
+
+import pytest
+
+from tests._server.host.drive import finished, wait_for
+from tests._server.host.live import key, open_host
+from tests._server.host.staleness import snapshot
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator
+ from pathlib import Path
+
+ from starlette.applications import Starlette
+
+ from marimo._config.config import OnCellChangeType
+ from marimo._core.protocol import RunOutcome
+ from tests._server.host.drive import Response
+ from tests._server.host.staleness import Outdated, Snapshot
+
+
+def notebook(*cells: str) -> str:
+ """A notebook source whose cells run `cells` in order."""
+ body = "".join(
+ "@app.cell\ndef _():\n"
+ + "".join(f" {line}\n" for line in code.splitlines())
+ for code in cells
+ )
+ return f"import marimo\napp = marimo.App()\n{body}"
+
+
+@dataclass
+class Client:
+ """A host client that refers to cells by name."""
+
+ app: Starlette
+ notebook_id: str
+ events: Response
+ cells: dict[str, str]
+ _keys: itertools.count[int] = field(default_factory=itertools.count)
+
+ async def run(
+ self,
+ *cells: str,
+ code: str | None = None,
+ outcome: RunOutcome = "succeeded",
+ ) -> None:
+ """Run the named cells, or code in the scratchpad, to `outcome`."""
+ body: dict[str, object] = (
+ {"code": code}
+ if code is not None
+ else {"cells": [{"id": self.cells[name]} for name in cells]}
+ )
+ accepted = await finished(
+ self.app,
+ "POST",
+ f"/notebooks/{self.notebook_id}/runtime/runs",
+ headers=key(f"run-{next(self._keys)}"),
+ body=json.dumps(body).encode(),
+ )
+ assert accepted.status == 202, accepted.body
+ run_id = accepted.json()["id"]
+
+ def completed(response: Response) -> list[dict[str, Any]]:
+ return [
+ run
+ for r in response.records
+ if (run := r.get("data", {}).get("run", {})).get("id")
+ == run_id
+ and run["status"] == "completed"
+ ]
+
+ await wait_for(self.events, lambda response: bool(completed(response)))
+ assert completed(self.events)[-1]["outcome"] == outcome
+
+ async def edit(self, cell: str, code: str) -> None:
+ edited = await finished(
+ self.app,
+ "POST",
+ f"/notebooks/{self.notebook_id}/edits",
+ headers=key(f"edit-{next(self._keys)}"),
+ body=json.dumps(
+ {
+ "changes": [
+ {
+ "kind": "put_cell",
+ "base_etag": "*",
+ "cell": {"id": self.cells[cell], "code": code},
+ }
+ ]
+ }
+ ).encode(),
+ )
+ assert edited.status == 200, edited.body
+
+ async def snapshot(self) -> Snapshot:
+ return await snapshot(self.app, self.notebook_id)
+
+ async def outdated(self) -> dict[str, Outdated]:
+ """Why each outdated cell is outdated, as a new client sees it."""
+ reasons = (await self.snapshot()).outdated()
+ return {
+ name: reasons[cell_id]
+ for name, cell_id in self.cells.items()
+ if cell_id in reasons
+ }
+
+
+async def client(
+ tmp_path: Path, *, on_cell_change: OnCellChangeType, **cells: str
+) -> AsyncIterator[Client]:
+ """Serve a notebook of the named cells and connect to it."""
+ async with open_host(
+ tmp_path, notebook(*cells.values()), on_cell_change=on_cell_change
+ ) as (app, notebook_id, events):
+ host = app.state.host_context.bridge.host
+ document = (await host.notebook(notebook_id)).document
+ ids = dict(zip(cells, (cell.id for cell in document), strict=True))
+ yield Client(app, notebook_id, events, ids)
+
+
+# Passes once the host publishes variables and dependencies.
+unpublished = pytest.mark.xfail(
+ strict=True, reason="the host does not publish variables yet"
+)
+
+
+@unpublished
+async def test_edits_and_reruns_outdate_dependents(tmp_path: Path) -> None:
+ async with client(
+ tmp_path, on_cell_change="lazy", x="x = 1", y="y = x + 1"
+ ) as c:
+ await c.run("x", "y")
+ assert await c.outdated() == {}
+
+ await c.edit("x", "x = 2")
+ assert await c.outdated() == {"x": "edited", "y": "edited"}
+
+ await c.run("x")
+ assert await c.outdated() == {"y": "replaced"}
+
+ await c.run("y")
+ assert await c.outdated() == {}
+
+
+async def test_autorun_leaves_every_result_current(tmp_path: Path) -> None:
+ async with client(
+ tmp_path, on_cell_change="autorun", x="x = 1", y="y = x + 1"
+ ) as c:
+ await c.run("x", "y")
+ await c.edit("x", "x = 2")
+ await c.run("x")
+ assert await c.outdated() == {}
+
+
+@unpublished
+async def test_state_updates_outdate_readers(tmp_path: Path) -> None:
+ async with client(
+ tmp_path,
+ on_cell_change="lazy",
+ mo="import marimo as mo",
+ state="get_x, set_x = mo.state(1)",
+ reader="y = get_x() + 1",
+ ) as c:
+ await c.run("mo", "state", "reader")
+ assert await c.outdated() == {}
+
+ await c.run(code="set_x(2)")
+ assert await c.outdated() == {"reader": "updated"}
+
+ await c.run("reader")
+ assert await c.outdated() == {}
+
+
+async def test_state_updates_rerun_readers_in_autorun(tmp_path: Path) -> None:
+ async with client(
+ tmp_path,
+ on_cell_change="autorun",
+ mo="import marimo as mo",
+ state="get_x, set_x = mo.state(1)",
+ reader="y = get_x() + 1",
+ ) as c:
+ await c.run("mo", "state", "reader")
+ await c.run(code="set_x(2)")
+ assert await c.outdated() == {}
+
+
+async def test_a_setter_that_reads_its_own_update_is_current(
+ tmp_path: Path,
+) -> None:
+ async with client(
+ tmp_path,
+ on_cell_change="lazy",
+ mo="import marimo as mo",
+ state="get_x, set_x = mo.state(1)",
+ setter="for _ in range(3):\n set_x(get_x() + 1)\nz = get_x()",
+ ) as c:
+ await c.run("mo", "state", "setter")
+ assert await c.outdated() == {}
+
+
+async def test_reimporting_keeps_dependents_current(tmp_path: Path) -> None:
+ async with client(
+ tmp_path,
+ on_cell_change="autorun",
+ imports="import math",
+ value="value = math.pi",
+ ) as c:
+ await c.run("imports", "value")
+ before = (await c.snapshot()).latest(c.cells["value"])
+
+ await c.edit("imports", "import math\nimport os")
+ await c.run("imports")
+ assert await c.outdated() == {}
+ # The dependent did not run again, so its result predates the edit.
+ assert (await c.snapshot()).latest(c.cells["value"]) == before
+
+
+@unpublished
+async def test_binding_a_missing_name_outdates_its_readers(
+ tmp_path: Path,
+) -> None:
+ async with client(
+ tmp_path,
+ on_cell_change="lazy",
+ binder="pass",
+ reader="y = missing + 1",
+ ) as c:
+ await c.run("binder", "reader", outcome="failed")
+ assert await c.outdated() == {}
+
+ await c.edit("binder", "missing = 1")
+ await c.run("binder")
+ assert await c.outdated() == {"reader": "replaced"}