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
Avoid ValueError when comparing embed defs with NumPy arrays (#7980)
Mukesh Dewangan50642e9bbd9b
diff --git a/marimo/_runtime/app/kernel_runner.py b/marimo/_runtime/app/kernel_runner.pyindex b54d26e18e..568fcfea70 100644--- a/marimo/_runtime/app/kernel_runner.py+++ b/marimo/_runtime/app/kernel_runner.py@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, Anyfrom marimo._ast.cell import CellImplfrom marimo._config.config import DEFAULT_CONFIG+from marimo._dependencies.dependencies import DependencyManagerfrom marimo._runtime.app.common import RunOutputfrom marimo._runtime.commands import (AppMetadata,@@ -25,6 +26,42 @@ if TYPE_CHECKING:from marimo._plugins.core.web_component import JSONType+def _defs_equal(a: dict[str, Any] | None, b: dict[str, Any] | None) -> bool:+ """Safely compare embed defs, handling NumPy arrays without ambiguous truth values."""++ if a is b:+ return True+ if a is None or b is None:+ return False+ if a.keys() != b.keys():+ return False++ for key in a:+ va, vb = a[key], b[key]++ # identical object+ if va is vb:+ continue++ try:+ if DependencyManager.numpy.imported():+ import numpy as np++ if isinstance(va, np.ndarray) and isinstance(vb, np.ndarray):+ if not np.array_equal(va, vb):+ return False+ continue++ if va != vb:+ return False++ except Exception:+ # Any ambiguous or unsafe comparison => treat as changed+ return False++ return True++class AppKernelRunner:"""Runs an app in a kernel context; used for composition."""@@ -116,7 +153,10 @@ class AppKernelRunner:def are_outputs_cached(self, defs: dict[str, Any] | None) -> bool:# The equality check is brittle but hashing isn't great either ...- return (defs == self._previously_seen_defs) and len(self.outputs) > 0+ return (+ _defs_equal(defs, self._previously_seen_defs)+ and len(self.outputs) > 0+ )def register_defs(self, defs: dict[str, Any] | None) -> None:self._previously_seen_defs = defsdiff --git a/tests/_runtime/runner/test_kernel_runner.py b/tests/_runtime/runner/test_kernel_runner.pynew file mode 100644index 0000000000..7ae6457a9e--- /dev/null+++ b/tests/_runtime/runner/test_kernel_runner.py@@ -0,0 +1,48 @@+from typing import cast++import pytest++from marimo._runtime.app.kernel_runner import AppKernelRunner+from marimo._types.ids import CellId_t+++def _make_runner():+ # Bypass __init__ since we only test caching logic+ runner = AppKernelRunner.__new__(AppKernelRunner)+ runner._previously_seen_defs = None+ runner._outputs = {cast(CellId_t, "cell-1"): "dummy"}+ return runner++[email protected]("numpy")+def test_numpy_defs_do_not_crash_and_invalidate_cache():+ runner = _make_runner()++ import numpy as np++ defs1 = {"arr": np.ones(1)}+ defs2 = {"arr": np.zeros(2)}++ runner._previously_seen_defs = defs1++ # Must not raise ValueError+ cached = runner.are_outputs_cached(defs2)++ assert cached is False++[email protected]("numpy")+def test_numpy_defs_equal_use_cache():+ runner = _make_runner()++ import numpy as np++ arr = np.array([1, 2, 3])+ defs1 = {"arr": arr}+ defs2 = {"arr": arr.copy()} # different object, same values++ runner._previously_seen_defs = defs1++ cached = runner.are_outputs_cached(defs2)++ assert cached is True