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.

fix: memory leak with temporary variables (#2334)

Akshay Agrawal5a903fd5320d
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index 26093233c8..58fce2ec1f 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -131,6 +131,8 @@ class CellImpl:
mod: ast.Module
defs: set[Name]
refs: set[Name]
+ temporaries: set[Name]
+
# metadata about definitions
variable_data: dict[Name, list[VariableData]]
deleted_refs: set[Name]
diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.py
index 4a6c564fe1..68746e6598 100644
--- a/marimo/_ast/compiler.py
+++ b/marimo/_ast/compiler.py
@@ -117,6 +117,7 @@ def compile_cell(
mod=module,
defs=set(),
refs=set(),
+ temporaries=set(),
variable_data={},
deleted_refs=set(),
language="python",
@@ -167,6 +168,7 @@ def compile_cell(
last_expr = compile(expr, filename, mode="eval", flags=flags)
nonlocals = {name for name in v.defs if not is_local(name)}
+ temporaries = v.defs - nonlocals
variable_data = {
name: v.variable_data[name]
for name in nonlocals
@@ -194,6 +196,7 @@ def compile_cell(
mod=module,
defs=nonlocals,
refs=v.refs,
+ temporaries=temporaries,
variable_data=variable_data,
import_workspace=ImportWorkspace(
is_import_block=is_import_block,
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index c6f82817d7..8c3b55406a 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -765,8 +765,12 @@ class Kernel:
missing_modules_before_deletion = (
self.module_registry.missing_modules()
)
+
+ temporaries = {
+ name: [VariableData(kind="variable")] for name in cell.temporaries
+ }
self._delete_variables(
- cell.variable_data,
+ {**cell.variable_data, **temporaries},
exclude_defs if exclude_defs is not None else set(),
)
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 758cf9e879..49cae4df8d 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -1120,6 +1120,14 @@ class TestExecution:
await k.run([er])
assert k.globals["x"] == "foo"
+ async def test_temporaries_deleted(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run([er := exec_req.get("_x = 1")])
+ assert k.globals[f"_cell_{er.cell_id}_x"] == 1
+ await k.run([ExecutionRequest(er.cell_id, "None")])
+ assert f"_cell_{er.cell_id}_x" not in k.globals
+
class TestStrictExecution:
@staticmethod