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.

Allow deleting variables defined by other cells (#5966)

Akshay Agrawaldd950a5e9b18
diff --git a/docs/guides/expensive_notebooks.md b/docs/guides/expensive_notebooks.md
index b54166a0d7..4d6bf8a40b 100644
--- a/docs/guides/expensive_notebooks.md
+++ b/docs/guides/expensive_notebooks.md
@@ -41,7 +41,7 @@ def __():
## Configure how marimo runs cells
-### Disabling cell autorun
+### Disable cell autorun
If you habitually work with very expensive notebooks, you can
[disable automatic
@@ -49,7 +49,7 @@ execution](../guides/configuration/runtime_configuration.md#disable-autorun-on-c
automatic execution is disabled, when you run a cell, marimo
marks dependent cells as stale instead of running them automatically.
-### Disabling autorun on startup
+### Disable autorun on startup
marimo autoruns notebooks on startup, with `marimo edit notebook.py` behaving
analogously to `python notebook.py`. This can also be disabled through the
@@ -62,7 +62,77 @@ helpful when you want to edit one part of a notebook without triggering
execution of other parts. See the
[reactivity guide](../guides/reactivity.md#disabling-cells) for more info.
-## Automatic snapshotting as HTML or ipynb
+## Manage memory
+
+Here are a few tips for managing the memory consumption of your notebooks,
+on host or GPU.
+
+### Wrap intermediate computations in functions
+
+By default, global variables live in the kernel memory. Intermediate variables
+that are defined in functions are cleaned up automatically.
+
+For example, if `X` is a temporary:
+
+**Do this:**
+
+```python
+def _():
+ X = torch.randn(1e4, 1e4, device='cuda')
+ Y = f(X)
+ return Y
+```
+
+**Don't do this:**
+
+```python
+X = torch.randn(1e4, 1e4, device='cuda')
+Y = f(X)
+# X still lives in program memory!
+```
+
+### Use `del` to remove variables from kernel memory
+
+
+Use the `del` operator to remove variables from kernel memory.
+
+**In a single cell.** Prefer deleting variables in the cell they were defined
+in. For example,
+if `X` is a temporary that you don't need after computing `Y`:
+
+```python
+X = torch.randn(1e4, 1e4, device='cuda')
+Y = f(X)
+del X
+```
+
+**In another cell.** Sometimes, computations are spread across multiple cells,
+and you only realize later on that you need to free memory that you've already
+allocated. In such cases you can still use the `del` keyword. For example:
+
+```python
+data = load_large_dataset()
+```
+
+```python
+derived_data = f(data)
+```
+
+```python
+del data
+```
+
+marimo inserts control dependences to make sure that variables are not deleted
+before they are used. When `del` is used to delete a variable that was defined
+in a another cell, the cell where `del` was used becomes a child of all other
+cells that reference that variable. In this case, that means marimo knows to
+run the third cell after the second cell, since the second cell references
+`data` and the third cell deletes it. However, once `data` is deleted,
+attempting to manually run the second cell will raise a `NameError`, and you'll
+need to re-run the defining cell in order to get your notebook back to a
+consistent state.
+
+## Automatically snapshot outputs as HTML or IPYNB
To keep a record of your cell outputs while working on your
notebook, you can configure notebooks to automatically save as HTML or ipynb
@@ -72,7 +142,7 @@ notebook's `.py` file). Snapshots are saved to a folder called
Learn more about exporting notebooks in our [exporting guide](../guides/exporting.md).
-## Caching
+## Cache expensive computations
marimo provides two decorators to cache the return values of expensive functions:
diff --git a/docs/guides/reactivity.md b/docs/guides/reactivity.md
index 12da1aba89..c6f7d7882f 100644
--- a/docs/guides/reactivity.md
+++ b/docs/guides/reactivity.md
@@ -185,6 +185,13 @@ _()
Here, the variables `plt`, `fig`, and `ax` aren't added to the globals.
+### Managing memory
+
+Because variable names must be unique, you cannot reassign variables as a means
+of freeing memory. Instead, manage memory by encapsulating code in functions or
+using the `del` operator. See our guide on [expensive
+notebooks](expensive_notebooks.md#manage-memory) to learn more.
+
## Configuring how marimo runs cells
Through the notebook settings menu, you can configure how and when marimo runs
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 2c8cf939a9..a0e0cb9646 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -45,7 +45,6 @@ from marimo._ast.cell import Cell, CellConfig, CellImpl
from marimo._ast.cell_manager import CellManager
from marimo._ast.errors import (
CycleError,
- DeleteNonlocalError,
MultipleDefinitionError,
SetupRootError,
UnparsableError,
@@ -568,13 +567,6 @@ class App:
"This app can't be run because it has multiple "
f"definitions of the name {multiply_defined_names[0]}"
)
- deleted_nonlocal_refs = self._graph.get_deleted_nonlocal_ref()
- if deleted_nonlocal_refs:
- raise DeleteNonlocalError(
- "This app can't be run because at least one cell "
- "deletes one of its refs (the ref's name is "
- f"{deleted_nonlocal_refs[0]})"
- )
self._execution_order = dataflow.topological_sort(
self._graph, list(self._cell_manager.valid_cell_ids())
)
diff --git a/marimo/_ast/errors.py b/marimo/_ast/errors.py
index 34e7b86be6..1eca5c240e 100644
--- a/marimo/_ast/errors.py
+++ b/marimo/_ast/errors.py
@@ -15,9 +15,5 @@ class MultipleDefinitionError(Exception):
pass
-class DeleteNonlocalError(Exception):
- pass
-
-
class UnparsableError(Exception):
pass
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index fb602f84ed..30d2391e8b 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -68,7 +68,6 @@ def _generate_server_api_schema() -> dict[str, Any]:
errors.CycleError,
errors.MultipleDefinitionError,
errors.ImportStarError,
- errors.DeleteNonlocalError,
errors.MarimoInterruptionError,
errors.MarimoInternalError,
errors.MarimoAncestorStoppedError,
diff --git a/marimo/_messaging/errors.py b/marimo/_messaging/errors.py
index cd61e4966d..33e1824eda 100644
--- a/marimo/_messaging/errors.py
+++ b/marimo/_messaging/errors.py
@@ -45,16 +45,6 @@ class ImportStarError:
return self.msg
-@dataclass
-class DeleteNonlocalError:
- name: str
- cells: tuple[CellId_t, ...]
- type: Literal["delete-nonlocal"] = "delete-nonlocal"
-
- def describe(self) -> str:
- return f"The variable '{self.name}' can't be deleted because it was defined by another cell"
-
-
@dataclass
class MarimoInterruptionError:
type: Literal["interruption"] = "interruption"
@@ -174,7 +164,6 @@ Error = Union[
CycleError,
MultipleDefinitionError,
ImportStarError,
- DeleteNonlocalError,
MarimoAncestorStoppedError,
MarimoAncestorPreventedError,
MarimoExceptionRaisedError,
diff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.py
index 8e7076adb2..9f71f866b3 100644
--- a/marimo/_runtime/dataflow.py
+++ b/marimo/_runtime/dataflow.py
@@ -152,6 +152,11 @@ class DirectedGraph:
self.children[cell_id] = children
self.siblings[cell_id] = siblings
self.parents[cell_id] = parents
+
+ # First, we process the variables that this cell defines. Any cell
+ # that refers to a defined variable becomes a child of this cell;
+ # any cell that defines a variable defined by this cell becomes
+ # a sibling.
for name, variable_data in cell.variable_data.items():
self.definitions.setdefault(name, set()).add(cell_id)
for sibling in self.definitions[name]:
@@ -178,15 +183,21 @@ class DirectedGraph:
for child in referring_cells:
self.parents[child].add(cell_id)
+ # Next, we process the cells references. The cell becomes a child
+ # of cells that define its referenced variables. We also have
+ # special logic for handling references that are deleted by this cell,
+ # since cells that delete variables that were defined elsewhere
+ # are made children of cells that reference that variable.
for name in cell.refs:
+ # First, for each referenced variable, we add cells that define
+ # that variable as parents
other_ids_defining_name: set[CellId_t] = (
self.definitions[name]
if name in self.definitions
else set()
) - set((cell_id,))
- # if other is empty, this means that the user is going to
- # get a NameError once the cell is run, unless the symbol
- # is say a builtin
+ # If other_ids_defining_name is empty, the user will get a
+ # NameError at runtime (unless the symbol is a builtin).
for other_id in other_ids_defining_name:
language = (
self.cells[other_id].variable_data[name][-1].language
@@ -202,6 +213,53 @@ class DirectedGraph:
if path:
self.cycles.add(tuple([(other_id, cell_id)] + path))
self.children[other_id].add(cell_id)
+
+ # Next, any cell that deletes this referenced variable is made
+ # a child of this cell. In particular, if a cell deletes a
+ # variable, it becomes a child of all other cells that
+ # reference that variable. This means that if two cells delete
+ # the same variable, they form a cycle.
+ #
+ # For example, two cells
+ #
+ # cell u: x
+ # cell v: del x
+ #
+ # v becomes a child of u.
+ #
+ # Another example:
+ #
+ # cell u: del x
+ # cell v: del x
+ #
+ # u and v form a cycle.
+ other_ids_deleting_name: set[CellId_t] = set(
+ cid
+ for cid in self.get_referring_cells(
+ name, language="python"
+ )
+ if name in self.cells[cid].deleted_refs
+ ) - set((cell_id,))
+ for v in other_ids_deleting_name:
+ path = self.get_path(v, cell_id)
+ if path:
+ self.cycles.add(tuple([(cell_id, v)] + path))
+ self.parents[v].add(cell_id)
+ children.update(other_ids_deleting_name)
+
+ # Finally, if this cell deletes a variable, we make it a child of
+ # all other cells that reference this variable.
+ for name in cell.deleted_refs:
+ referring_cells = self.get_referring_cells(
+ name, language="python"
+ ) - set((cell_id,))
+ for other_id in referring_cells:
+ parents.add(other_id)
+ path = self.get_path(cell_id, other_id)
+ if path:
+ self.cycles.add(tuple([(other_id, cell_id)] + path))
+ self.children[other_id].add(cell_id)
+
LOGGER.debug("Registered cell %s and released graph lock", cell_id)
if self.is_any_ancestor_stale(cell_id):
self.set_stale(set([cell_id]))
diff --git a/marimo/_runtime/runner/cell_runner.py b/marimo/_runtime/runner/cell_runner.py
index e3cfda9594..8c81110786 100644
--- a/marimo/_runtime/runner/cell_runner.py
+++ b/marimo/_runtime/runner/cell_runner.py
@@ -354,9 +354,19 @@ class Runner:
)
exception = output
elif blamed_cell != cell_id:
+ possibly_deleted = any(
+ ref in cell.deleted_refs
+ for cell in self.graph.cells.values()
+ )
+
+ deleted_message = (
+ " Another cell may have deleted it with the del operator."
+ if possibly_deleted
+ else ""
+ )
output = MarimoExceptionRaisedError(
- f"marimo came across the undefined variable `{ref}` "
- "during runtime. Definition expected in cell : ",
+ f"Name `{ref}` is not defined.{deleted_message} "
+ "It was expected to be defined in ",
"NameError",
blamed_cell,
)
diff --git a/marimo/_runtime/runner/hooks_on_finish.py b/marimo/_runtime/runner/hooks_on_finish.py
index 3c13ef271d..7ef07ac45e 100644
--- a/marimo/_runtime/runner/hooks_on_finish.py
+++ b/marimo/_runtime/runner/hooks_on_finish.py
@@ -71,12 +71,12 @@ def _send_cancellation_errors(runner: cell_runner.Runner) -> None:
blamed_cell=exception.blamed_cell,
)
else:
- exception_type = type(runner.exceptions[raising_cell]).__name__
+ exception_type = type(exception).__name__
data = MarimoExceptionRaisedError(
msg=(
f"An ancestor raised an exception ({exception_type}): "
),
- exception_type=exception_type,
+ exception_type="Ancestor raised",
raising_cell=raising_cell,
)
CellOp.broadcast_error(
diff --git a/marimo/_runtime/validate_graph.py b/marimo/_runtime/validate_graph.py
index 31a1b59110..1c4bf46576 100644
--- a/marimo/_runtime/validate_graph.py
+++ b/marimo/_runtime/validate_graph.py
@@ -7,7 +7,6 @@ from collections import defaultdict
from marimo._ast.names import SETUP_CELL_NAME
from marimo._messaging.errors import (
CycleError,
- DeleteNonlocalError,
Error,
MultipleDefinitionError,
SetupRootError,
@@ -37,23 +36,6 @@ def check_for_multiple_definitions(
return errors
-def check_for_delete_nonlocal(
- graph: DirectedGraph,
-) -> dict[CellId_t, list[DeleteNonlocalError]]:
- """Check whether cells delete their refs."""
- errors = defaultdict(list)
- for cid in graph.cells.keys():
- for name in graph.cells[cid].deleted_refs:
- if name in graph.definitions:
- errors[cid].append(
- DeleteNonlocalError(
- name=str(name),
- cells=tuple(graph.definitions[name]),
- )
- )
- return errors
-
-
def check_for_invalid_root(
graph: DirectedGraph,
) -> dict[CellId_t, list[SetupRootError]]:
@@ -95,7 +77,18 @@ def check_for_cycles(graph: DirectedGraph) -> dict[CellId_t, list[CycleError]]:
cycle_with_vars = tuple(
(
edge[0],
- sorted(graph.cells[edge[0]].defs & graph.cells[edge[1]].refs),
+ sorted(
+ set(
+ list(
+ graph.cells[edge[0]].defs
+ & graph.cells[edge[1]].refs
+ )
+ + list(
+ graph.cells[edge[0]].refs
+ & graph.cells[edge[1]].deleted_refs
+ )
+ )
+ ),
edge[1],
)
for edge in cycle
@@ -115,7 +108,6 @@ def check_for_errors(
that is involved in an error.
"""
multiple_definition_errors = check_for_multiple_definitions(graph)
- delete_nonlocal_errors = check_for_delete_nonlocal(graph)
cycle_errors = check_for_cycles(graph)
invalid_root_errors = check_for_invalid_root(graph)
@@ -123,7 +115,6 @@ def check_for_errors(
for cid in set(
itertools.chain(
multiple_definition_errors.keys(),
- delete_nonlocal_errors.keys(),
cycle_errors.keys(),
invalid_root_errors.keys(),
)
@@ -132,7 +123,6 @@ def check_for_errors(
itertools.chain(
multiple_definition_errors[cid],
cycle_errors[cid],
- delete_nonlocal_errors[cid],
invalid_root_errors[cid],
)
)
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index 854e002679..9ee9dd0691 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -707,23 +707,6 @@ components:
required:
- cellId
type: object
- DeleteNonlocalError:
- properties:
- cells:
- items:
- type: string
- type: array
- name:
- type: string
- type:
- enum:
- - delete-nonlocal
- type: string
- required:
- - name
- - cells
- - type
- type: object
DeleteSecretRequest:
properties:
key:
@@ -765,7 +748,6 @@ components:
- $ref: '#/components/schemas/CycleError'
- $ref: '#/components/schemas/MultipleDefinitionError'
- $ref: '#/components/schemas/ImportStarError'
- - $ref: '#/components/schemas/DeleteNonlocalError'
- $ref: '#/components/schemas/MarimoAncestorStoppedError'
- $ref: '#/components/schemas/MarimoAncestorPreventedError'
- $ref: '#/components/schemas/MarimoExceptionRaisedError'
@@ -2749,7 +2731,7 @@ components:
type: object
info:
title: marimo API
- version: 0.14.15
+ version: 0.14.16
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 987ea8a510..78d444dd4c 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -2820,12 +2820,6 @@ export interface components {
DeleteCellRequest: {
cellId: string;
};
- DeleteNonlocalError: {
- cells: string[];
- name: string;
- /** @enum {string} */
- type: "delete-nonlocal";
- };
DeleteSecretRequest: {
key: string;
};
@@ -2845,7 +2839,6 @@ export interface components {
| components["schemas"]["CycleError"]
| components["schemas"]["MultipleDefinitionError"]
| components["schemas"]["ImportStarError"]
- | components["schemas"]["DeleteNonlocalError"]
| components["schemas"]["MarimoAncestorStoppedError"]
| components["schemas"]["MarimoAncestorPreventedError"]
| components["schemas"]["MarimoExceptionRaisedError"]
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index d34bcef028..a1e9c0be87 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -18,7 +18,6 @@ from marimo._ast.app import (
from marimo._ast.app_config import _AppConfig
from marimo._ast.errors import (
CycleError,
- DeleteNonlocalError,
MultipleDefinitionError,
SetupRootError,
UnparsableError,
@@ -195,7 +194,7 @@ class TestApp:
app.run()
@staticmethod
- def test_delete_nonlocal_missing_args_rets() -> None:
+ def test_delete_nonlocal_ok() -> None:
app = App()
@app.cell
@@ -206,8 +205,8 @@ class TestApp:
def two() -> None:
del x # noqa: F841, F821
- with pytest.raises(DeleteNonlocalError):
- app.run()
+ # smoke test, no error raised
+ app.run()
@staticmethod
def test_unparsable_cell() -> None:
diff --git a/tests/_messaging/test_messaging_errors.py b/tests/_messaging/test_messaging_errors.py
index bc8ddbeae4..ec5b3a9986 100644
--- a/tests/_messaging/test_messaging_errors.py
+++ b/tests/_messaging/test_messaging_errors.py
@@ -3,7 +3,6 @@ from __future__ import annotations
from marimo._messaging.errors import (
CycleError,
- DeleteNonlocalError,
ImportStarError,
MarimoAncestorPreventedError,
MarimoAncestorStoppedError,
@@ -50,14 +49,6 @@ class TestErrorClasses:
assert error.type == "import-star"
assert error.describe() == "Cannot use import * in this context"
- def test_delete_nonlocal_error(self) -> None:
- error = DeleteNonlocalError(name="test_var", cells=("cell1", "cell2"))
-
- # Test properties
- assert error.type == "delete-nonlocal"
- assert "test_var" in error.describe()
- assert "can't be deleted" in error.describe()
-
def test_marimo_interruption_error(self) -> None:
error = MarimoInterruptionError()
diff --git a/tests/_runtime/test_dataflow.py b/tests/_runtime/test_dataflow.py
index 80e1727d74..46e835c209 100644
--- a/tests/_runtime/test_dataflow.py
+++ b/tests/_runtime/test_dataflow.py
@@ -974,6 +974,44 @@ def test_cycles() -> None:
assert not graph.cycles
+def test_del_del_cycle():
+ """Two variables that delete the same variable form a cycle."""
+ graph = dataflow.DirectedGraph()
+
+ graph.register_cell("0", parse_cell("del x"))
+ graph.register_cell("1", parse_cell("del x"))
+ assert len(graph.cycles) == 1
+ assert set(list(graph.cycles)[0]) == set((("0", "1"), ("1", "0")))
+
+
+def test_del_ref_cycle():
+ """One cell deletes a variable and defines another, the other refs both."""
+ graph = dataflow.DirectedGraph()
+
+ graph.register_cell("0", parse_cell("x = 1"))
+ graph.register_cell("1", parse_cell("del x; y = 1"))
+ graph.register_cell("2", parse_cell("z = x + y"))
+ assert len(graph.cycles) == 1
+ assert set(list(graph.cycles)[0]) == set([("1", "2"), ("2", "1")])
+
+
+def test_del_child_of_ref():
+ """Cells that delete a variable become a child of cells that reference it."""
+ graph = dataflow.DirectedGraph()
+
+ graph.register_cell("0", parse_cell("del x"))
+ graph.register_cell("1", parse_cell("x"))
+ graph.register_cell("2", parse_cell("x = 1"))
+ assert graph.parents["0"] == set(["1", "2"])
+ assert graph.children["0"] == set()
+
+ assert graph.parents["1"] == set(["2"])
+ assert graph.children["1"] == set(["0"])
+
+ assert graph.parents["2"] == set([])
+ assert graph.children["2"] == set(["0", "1"])
+
+
def test_get_path() -> None:
"""Test the get_path method."""
graph = dataflow.DirectedGraph()
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index b979a55488..1352abbb56 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -16,7 +16,6 @@ from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.cell_output import CellChannel
from marimo._messaging.errors import (
CycleError,
- DeleteNonlocalError,
Error,
MarimoStrictExecutionError,
MarimoSyntaxError,
@@ -712,8 +711,15 @@ class TestExecution:
else:
assert not k.errors
- async def test_delete_nonlocal_error(self, any_kernel: Kernel) -> None:
+ async def test_delete_nonlocal_ok(self, any_kernel: Kernel) -> None:
k = any_kernel
+ if k.execution_type == "strict":
+ # `x` does not get removed from memory in strict mode; strict
+ # execution is experimental and not widely used nor maintained, so
+ # we're okay with this not working.
+ pytest.skip(
+ "Deleting variables does not work in strict execution."
+ )
await k.run(
[
ExecutionRequest(cell_id="0", code="x=0"),
@@ -721,25 +727,59 @@ class TestExecution:
er := ExecutionRequest(cell_id="2", code="z = y + 1"),
]
)
- assert "y" not in k.globals
- assert "z" not in k.globals
- if k.execution_type == "strict":
- assert set(k.errors.keys()) == {"1", "2"}
- else:
- assert set(k.errors.keys()) == {"1"}
- assert k.errors["1"] == (DeleteNonlocalError("x", ("0",)),)
+ assert "x" not in k.globals
+ assert "y" in k.globals
+ assert "z" in k.globals
+ assert not k.errors
- # fix cell 1, should run cell 1 and 2
- await k.run([ExecutionRequest(cell_id="1", code="y=1")])
- if k.lazy():
- assert k.graph.cells[er.cell_id].stale
- await k.run([er])
+ async def test_delete_nonlocal_multiple_not_ok(self, k: Kernel) -> None:
+ await k.run(
+ [
+ ExecutionRequest(cell_id="0", code="del x"),
+ ExecutionRequest(cell_id="1", code="del x"),
+ ]
+ )
+ assert set(k.errors.keys()) == {"0", "1"}
+ _check_edges(k.errors["0"][0], [("0", ["x"], "1"), ("1", ["x"], "0")])
+ _check_edges(k.errors["1"][0], [("0", ["x"], "1"), ("1", ["x"], "0")])
- assert not k.graph.cells[er.cell_id].stale
- assert k.globals["y"] == 1
- assert k.globals["z"] == 2
+ async def test_delete_nonlocal_incremental_ref_raises_name_error(
+ self, k: Kernel
+ ) -> None:
+ await k.run(
+ [
+ er := ExecutionRequest(cell_id="0", code="x=0"),
+ ExecutionRequest(cell_id="1", code="del x; y = 1"),
+ ]
+ )
+ assert "x" not in k.globals
+ assert "y" in k.globals
assert not k.errors
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="2",
+ code="""
+try:
+ z = x + 1
+ name_error = False
+except NameError:
+ name_error = True
+""",
+ )
+ ]
+ )
+ assert "z" not in k.globals
+ assert k.globals["name_error"]
+
+ # Run x's defining cell. This time, cell "2" will run before cell "1".
+ await k.run([er])
+ assert "x" not in k.globals
+ assert "y" in k.globals
+ assert k.globals["z"] == 1
+ assert not k.globals["name_error"]
+
async def test_import_module_as_local_var(
self, any_kernel: Kernel
) -> None:
@@ -757,44 +797,6 @@ class TestExecution:
assert "_sys" not in k.globals
assert k.globals["msize"] == sys.maxsize
- async def test_defs_with_no_definers_are_removed_from_cell(
- self, any_kernel: Kernel
- ) -> None:
- k = any_kernel
- await k.run(
- [
- ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code="del x"),
- ]
- )
- assert set(k.errors.keys()) == {"1"}
- assert k.errors["1"] == (DeleteNonlocalError("x", ("0",)),)
-
- # Delete the cell that defines x. There shouldn't be any more errors
- # because x no longer exists.
- await k.delete_cell(DeleteCellRequest(cell_id="0"))
- if k.execution_type != "strict":
- assert not k.errors
-
- # Add x back in.
- await k.run([ExecutionRequest(cell_id="2", code="x=0")])
- assert set(k.errors.keys()) == {"1"}
- assert k.errors["1"] == (DeleteNonlocalError("x", ("2",)),)
-
- # Repair graph
- await k.run([er := ExecutionRequest(cell_id="1", code="y = x + 1")])
- assert not k.errors
- assert k.globals["y"] == 1
-
- # Make sure graph is tracking x again and update propagates
- await k.run([ExecutionRequest(cell_id="2", code="x = 1")])
- assert not k.errors
- if k.lazy():
- assert k.graph.cells[er.cell_id].stale
- await k.run([er])
- assert not k.graph.cells[er.cell_id].stale
- assert k.globals["y"] == 2
-
async def test_cell_transitioned_to_error_is_not_stale(
self, lazy_kernel: Kernel
) -> None:
@@ -1510,7 +1512,7 @@ class TestExecution:
)
else:
assert (
- "marimo came across the undefined variable `C` during runtime."
+ "Name `C` is not defined. It was expected to be defined in"
in k.stream.messages[-2][1]["output"]["data"][0]["msg"]
)
assert "NameError" in k.stderr.messages[0]
diff --git a/tests/_runtime/test_trace.py b/tests/_runtime/test_trace.py
index bfe796bf49..3fe8cca26c 100644
--- a/tests/_runtime/test_trace.py
+++ b/tests/_runtime/test_trace.py
@@ -271,7 +271,7 @@ class TestAppTrace:
)
else:
assert (
- "marimo came across the undefined variable `C` during runtime."
+ "Name `C` is not defined."
in k.stream.messages[-2][1]["output"]["data"][0]["msg"]
)
assert "NameError" in k.stderr.messages[0]
diff --git a/tests/_runtime/test_validate_graph.py b/tests/_runtime/test_validate_graph.py
index 047afe86af..7643dffcf8 100644
--- a/tests/_runtime/test_validate_graph.py
+++ b/tests/_runtime/test_validate_graph.py
@@ -8,7 +8,6 @@ from marimo._ast import compiler
from marimo._ast.names import SETUP_CELL_NAME
from marimo._messaging.errors import (
CycleError,
- DeleteNonlocalError,
MultipleDefinitionError,
SetupRootError,
)
@@ -70,15 +69,6 @@ def test_underscore_variables_are_private() -> None:
assert not errors
-def test_delete_nonlocal_error() -> None:
- graph = dataflow.DirectedGraph()
- graph.register_cell("0", parse_cell("x = 0"))
- graph.register_cell("1", parse_cell("del x"))
- errors = check_for_errors(graph)
- assert set(errors.keys()) == set(["1"])
- assert errors["1"] == (DeleteNonlocalError(name="x", cells=("0",)),)
-
-
def test_two_node_cycle() -> None:
graph = dataflow.DirectedGraph()
graph.register_cell("0", parse_cell("x = y"))
@@ -138,6 +128,26 @@ def test_cycle_and_multiple_def() -> None:
assert multiple_definition_error.cells == (str((int(cell) + 1) % 2),)
+def test_del_ref_cycle() -> None:
+ graph = dataflow.DirectedGraph()
+
+ graph.register_cell("0", parse_cell("x = 1"))
+ graph.register_cell("1", parse_cell("del x; y = 1"))
+ graph.register_cell("2", parse_cell("z = x + y"))
+ errors = check_for_errors(graph)
+ # Edge ordering in returned error is not deterministic, so we list both
+ # possible cycles
+ expected_cycle = [
+ CycleError(edges_with_vars=(("2", ["x"], "1"), ("1", ["y"], "2"))),
+ CycleError(edges_with_vars=(("1", ["y"], "2"), ("2", ["x"], "1"))),
+ ]
+
+ assert len(errors["1"]) == 1
+ assert len(errors["2"]) == 1
+ assert errors["1"][0] in expected_cycle
+ assert errors["2"][0] in expected_cycle
+
+
def test_setup_has_refs() -> None:
graph = dataflow.DirectedGraph()
graph.register_cell(SETUP_CELL_NAME, parse_cell("z = y"))