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
Record staleness reads on .code access only (#9655)
Trevor Manzd0ed8b20df82
diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.pyindex 9948a9ff21..e5191a85dd 100644--- a/marimo/_code_mode/_context.py+++ b/marimo/_code_mode/_context.py@@ -92,7 +92,7 @@ from marimo._types.ids import CellId_t, UIElementIdfrom marimo._utils.formatter import DefaultFormatterif TYPE_CHECKING:- from collections.abc import Iterator, Sequence+ from collections.abc import Callable, Iterator, Sequencefrom os import PathLikefrom types import TracebackType@@ -219,7 +219,7 @@ def get_context(When False (the default), `edit_cell` raises:class:`StaleCellError` if the agent tries to overwrite a cellwhose code has changed since the agent last read it (e.g. via- `ctx.cells[cell_id]`). Set to True to overwrite blindly —+ `ctx.cells[cell_id].code`). Set to True to overwrite blindly —useful when the agent intentionally discards prior content."""runtime_ctx = _get_runtime_context()@@ -296,7 +296,13 @@ class NotebookCell:Same frozen-snapshot caveat as `output`."""- __slots__ = ("_cell", "_graph_errors", "_impl", "_outputs")+ __slots__ = (+ "_cell",+ "_graph_errors",+ "_impl",+ "_outputs",+ "_record_read",+ )def __init__(self,@@ -304,11 +310,13 @@ class NotebookCell:cell_impl: CellRuntimeState | None,graph_errors: tuple[Error, ...] = (),outputs: CellOutputs | None = None,+ record_read: Callable[[], None] | None = None,) -> None:self._cell = cellself._impl = cell_implself._graph_errors = graph_errorsself._outputs = outputs+ self._record_read = record_read# -- document properties (delegated) --@@ -320,6 +328,8 @@ class NotebookCell:@propertydef code(self) -> str:"""The current source code of the cell."""+ if self._record_read is not None:+ self._record_read()return self._cell.code@property@@ -489,7 +499,6 @@ class _CellsView:def _cell_view(self, cell: _NotebookCell) -> NotebookCell:"""Wrap a document cell with runtime state from the graph."""- self._ctx._note_read(cell.id, cell.version)try:graph = self._ctx.graphimpl = graph.cells.get(cell.id)@@ -499,11 +508,16 @@ class _CellsView:impl = Nonegraph_errors = ()outputs = None++ def record_read() -> None:+ self._ctx._note_read(cell.id, cell.version)+return NotebookCell(cell,impl,graph_errors=graph_errors,outputs=outputs,+ record_read=record_read,)def _cell_ids(self) -> list[CellId_t]:@@ -624,7 +638,9 @@ class _CellsView:def _fmt(i: int, c: _NotebookCell) -> str:cv = self._cell_view(c)- first_line = c.code.split("\n", 1)[0]+ # Read through the wrapper so the staleness tracker sees+ # the preview as a read of the cell's source.+ first_line = cv.code.split("\n", 1)[0]code_preview = first_line[:50]if len(first_line) > 50:code_preview += "..."diff --git a/tests/_code_mode/test_staleness.py b/tests/_code_mode/test_staleness.pyindex 8258a7a386..e6fa5be4ab 100644--- a/tests/_code_mode/test_staleness.py+++ b/tests/_code_mode/test_staleness.py@@ -308,38 +308,98 @@ class TestSetupCellMigration:class TestCellsViewReadRecording:- async def test_iteration_records_reads(self, k: Kernel) -> None:+ """Reads record on `.code` access, never on wrapper construction.++ Indexing, iteration, find, and grep all just hand out wrappers — they+ do not by themselves prove the agent has seen the code. Without this+ invariant, `first = ctx.cells[0]; ctx.edit_cell(first.id, ...)` would+ blindly clobber code the agent never looked at.+ """++ async def test_indexing_alone_does_not_satisfy_staleness(+ self, k: Kernel+ ) -> None:+ await _seed(k, "0", "a = 1")+ with _ctx(k) as ctx:+ async with ctx as nb:+ first = nb.cells[0] # wrapper only — no .code access+ with pytest.raises(StaleCellError):+ nb.edit_cell(first.id, "a = 2")++ async def test_indexing_then_code_access_satisfies_staleness(+ self, k: Kernel+ ) -> None:+ await _seed(k, "0", "a = 1")+ with _ctx(k) as ctx:+ async with ctx as nb:+ first = nb.cells[0]+ _ = first.code # this is the access that counts+ nb.edit_cell(first.id, "a = 2")++ async def test_iteration_alone_does_not_record_reads(+ self, k: Kernel+ ) -> None:await _seed(k, "0", "a = 1")await _seed(k, "1", "b = 2")with _ctx(k) as ctx:async with ctx as nb:for _ in nb.cells:pass- nb.edit_cell("0", "a = 99")- nb.edit_cell("1", "b = 99")+ with pytest.raises(StaleCellError):+ nb.edit_cell("0", "a = 99")- async def test_find_records_reads_for_matches_only(+ async def test_iteration_with_code_access_records_reads(self, k: Kernel) -> None:+ await _seed(k, "0", "a = 1")+ await _seed(k, "1", "b = 2")+ with _ctx(k) as ctx:+ async with ctx as nb:+ for cell in nb.cells:+ _ = cell.code+ nb.edit_cell("0", "a = 99")+ nb.edit_cell("1", "b = 99")++ async def test_find_does_not_record_reads(self, k: Kernel) -> None:+ # find returns matched wrappers but the agent has not seen the+ # source — only that a substring matched. Editing without a+ # follow-up `.code` read must still raise.await _seed(k, "0", "alpha = 1")await _seed(k, "1", "beta = 2")with _ctx(k) as ctx:async with ctx as nb:matches = nb.cells.find("alpha")assert len(matches) == 1- nb.edit_cell("0", "alpha = 99")with pytest.raises(StaleCellError):- nb.edit_cell("1", "beta = 99")+ nb.edit_cell("0", "alpha = 99")- async def test_grep_records_reads_for_matches_only(- self, k: Kernel- ) -> None:+ async def test_grep_does_not_record_reads(self, k: Kernel) -> None:await _seed(k, "0", "alpha = 1")await _seed(k, "1", "beta = 2")with _ctx(k) as ctx:async with ctx as nb:matches = nb.cells.grep(r"alpha")assert len(matches) == 1- nb.edit_cell("0", "alpha = 99")with pytest.raises(StaleCellError):- nb.edit_cell("1", "beta = 99")+ nb.edit_cell("0", "alpha = 99")++ async def test_repr_records_reads(self, k: Kernel) -> None:+ # `repr(ctx.cells)` shows first-line code previews of every cell,+ # so the agent has seen source snippets — editing without a+ # separate read must succeed.+ await _seed(k, "0", "a = 1")+ await _seed(k, "1", "b = 2")+ with _ctx(k) as ctx:+ async with ctx as nb:+ _ = repr(nb.cells)+ nb.edit_cell("0", "a = 99")+ nb.edit_cell("1", "b = 99")++ async def test_notebook_cell_repr_records_read(self, k: Kernel) -> None:+ # NotebookCell.__repr__ embeds a code preview via `self.code`, so+ # repr-ing a single cell counts as a read.+ await _seed(k, "0", "a = 1")+ with _ctx(k) as ctx:+ async with ctx as nb:+ _ = repr(nb.cells[0])+ nb.edit_cell("0", "a = 2")