From ac271b0ed24564a045afe27707ad569caf9b11bd Mon Sep 17 00:00:00 2001 From: Dave Borowitz Date: Tue, 1 Dec 2026 20:24:52 -0800 Subject: [PATCH] feat(packaging): include managed-spark-cell-monitoring in interactive extra --- DEVELOPING.md | 7 +- README.md | 13 +- .../cloud/managed_spark_connect/_ipython.py | 31 ++-- setup.py | 1 + tests/unit/test_cell_monitoring.py | 149 ++++++++++++++++-- tests/unit/test_init.py | 107 +++++++++---- 6 files changed, 249 insertions(+), 59 deletions(-) diff --git a/DEVELOPING.md b/DEVELOPING.md index 6e42182b..4a86cbba 100644 --- a/DEVELOPING.md +++ b/DEVELOPING.md @@ -56,11 +56,12 @@ without `-n auto` (~8 minutes total). ## Testing the Interactive Extras The dependencies of the interactive extras (`explore_dataframe`, `%dpip`, -`%%sparksql`) live in the `interactive` extra +`%%sparksql`, `%cellmonitor`) live in the `interactive` extra (`pip install '.[client,interactive]'`), and `requirements-dev.txt` already includes them along with `pyspark-client`. The tests in -`tests/unit/test_init.py` assume `google-colabsqlviz`, `ipython`, `sqlparse` -and `traitlets` are importable and will fail, not skip, if they are not. +`tests/unit/test_init.py` assume `google-colabsqlviz`, `ipython`, +`managed-spark-cell-monitoring`, `sqlparse` and `traitlets` are importable and +will fail, not skip, if they are not. Missing dependencies are simulated within the tests themselves, by setting `sys.modules[name] = None`. diff --git a/README.md b/README.md index 484c1b5e..393dca3a 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ requiring additional steps. For notebooks and interactive development, install with the `client` and `interactive` extras to get the lightweight `pyspark-client` package along with -the interactive extras (`explore_dataframe()`, `%dpip`, `%%sparksql`, and `%cellmonitor` when `managed-spark-cell-monitoring` is installed): +the interactive extras (`explore_dataframe()`, `%dpip`, `%%sparksql`, and `%cellmonitor`): ```sh pip install 'google-cloud-spark-connect[client,interactive]' @@ -265,12 +265,11 @@ up a few interactive conveniences: [google-colabsqlviz](https://pypi.org/project/google-colabsqlviz/) is injected into your notebook globals. - The [`%dpip` and `%%sparksql`](#bundled-magics) magics are loaded. -- When `managed-spark-cell-monitoring` is installed separately (it is not pulled - in by the `interactive` extra; install e.g. `pip install 'managed-spark-cell-monitoring[connect]'` - or use a runtime image that pre-installs it), `%cellmonitor` is loaded - automatically. On supported Spark Connect runtimes it renders an inline cell - monitoring widget and suppresses the legacy per-operation links and `tqdm` - progress bars, falling back automatically on unsupported runtimes. +- `%cellmonitor` from + [managed-spark-cell-monitoring](https://pypi.org/project/managed-spark-cell-monitoring/) + is loaded automatically. On supported Spark Connect runtimes it renders an + inline cell monitoring widget and suppresses the legacy per-operation links + and `tqdm` progress bars, falling back automatically on unsupported runtimes. ```python import google.cloud.managed_spark_connect # extras load here diff --git a/google/cloud/managed_spark_connect/_ipython.py b/google/cloud/managed_spark_connect/_ipython.py index 752b94dd..7753d26e 100644 --- a/google/cloud/managed_spark_connect/_ipython.py +++ b/google/cloud/managed_spark_connect/_ipython.py @@ -31,16 +31,22 @@ # Module that must be installed for explore_dataframe() to be injected. _COLABSQLVIZ_MODULE = "google.colabsqlviz" -# (extension module, ((magic kind, magic name), ...)). Each extension is only -# loaded if its module is installed. +# (extension module, magic package prefix, ((magic kind, magic name), ...), +# magics_only). Each extension is only loaded if its module is installed. +# Pure-magic extensions can be skipped once all their magics already exist; +# extensions that also attach shell hooks still need to load. _EXTRAS_EXTENSIONS = ( ( + "google.cloud.managed_spark_magics", "google.cloud.managed_spark_magics", (("line", "dpip"), ("line", "sparksql"), ("cell", "sparksql")), + True, ), ( "managed_spark_cell_monitoring.spark_connect", + "managed_spark_cell_monitoring", (("line", "cellmonitor"),), + False, ), ) @@ -248,7 +254,11 @@ def _is_from_module(fn: Any, module: str) -> bool: def _is_extension_loaded( - ip: Any, ext_name: str, magics: Sequence[Tuple[str, str]] + ip: Any, + ext_name: str, + magics: Sequence[Tuple[str, str]], + *, + magics_only: bool = True, ) -> bool: mod = sys.modules.get(ext_name) if mod is not None and getattr( @@ -261,8 +271,9 @@ def _is_extension_loaded( if isinstance(loaded, (set, dict, list, tuple)) and ext_name in loaded: return True - # Every magic it would add is already there, so it has nothing to offer. - return len(_present_magics(ip, magics)) == len(magics) + # A pure-magic extension has nothing left to offer once every magic it + # would add is already present; hook-attaching extensions still need to load. + return magics_only and len(_present_magics(ip, magics)) == len(magics) def _print_extras_loaded(loaded: List[str]) -> None: @@ -351,10 +362,12 @@ def _load_extras_for_shell(ip: Any) -> None: # 2. Load magic extensions ext_mgr = getattr(ip, "extension_manager", None) if ext_mgr is not None and hasattr(ext_mgr, "load_extension"): - for ext_name, magics in _EXTRAS_EXTENSIONS: + for ext_name, _magic_pkg, magics, magics_only in _EXTRAS_EXTENSIONS: try: if ext_name in state.loaded_extensions or ( - _is_extension_loaded(ip, ext_name, magics) + _is_extension_loaded( + ip, ext_name, magics, magics_only=magics_only + ) ): continue if not _is_module_available(ext_name): @@ -414,7 +427,7 @@ def _unload_extras_for_shell(ip: Any) -> None: ext_mgr = getattr(ip, "extension_manager", None) loaded = getattr(ext_mgr, "loaded", None) - for ext_name, magics in _EXTRAS_EXTENSIONS: + for ext_name, magic_pkg, magics, _magics_only in _EXTRAS_EXTENSIONS: if ext_name in state.loaded_extensions: added = state.added_magics.pop(ext_name, ()) # Magics from this extension that were already present before we @@ -438,7 +451,7 @@ def _unload_extras_for_shell(ip: Any) -> None: for kind, name in added: kind_dict = shell_magics.get(kind) if isinstance(kind_dict, dict) and _is_from_module( - kind_dict.get(name), ext_name + kind_dict.get(name), magic_pkg ): del kind_dict[name] if isinstance(loaded, set): diff --git a/setup.py b/setup.py index f1ed67a7..e1f482c0 100644 --- a/setup.py +++ b/setup.py @@ -125,6 +125,7 @@ def run(self) -> None: # managed_spark_magics; previously these only arrived transitively # via google-colabsqlviz. "ipython>=7.34.0", + "managed-spark-cell-monitoring[connect]>=1.1.0,<2.0", # Statement splitting and parameter detection in %%sparksql. "sqlparse>=0.5.0", "traitlets>=5.1", diff --git a/tests/unit/test_cell_monitoring.py b/tests/unit/test_cell_monitoring.py index 85519e8d..fb7c2536 100644 --- a/tests/unit/test_cell_monitoring.py +++ b/tests/unit/test_cell_monitoring.py @@ -880,19 +880,24 @@ def _make_bar(**kw): handler([StageInfo(1, 4, 4, 0, True)], 0, "op-p", True) bars[1].close.assert_called_once() - def test_ipython_extras_loads_and_unloads_cellmonitor_extension(self): + def _setup_fake_cellmonitor_shell(self): from IPython.core.interactiveshell import InteractiveShell from google.cloud.managed_spark_connect import _ipython fake_ext = types.ModuleType(_cell_monitoring._CELL_MONITOR_EXTENSION) + loaded: List[Any] = [] unloaded: List[Any] = [] poller_created: List[Any] = [] def _load_ext(ip): + loaded.append(ip) + def cellmonitor(line=""): return line - cellmonitor.__module__ = _cell_monitoring._CELL_MONITOR_EXTENSION + # Match the real package where register_cellmonitor_magic lives on + # managed_spark_cell_monitoring rather than .spark_connect. + cellmonitor.__module__ = "managed_spark_cell_monitoring" ip.register_magic_function( cellmonitor, magic_kind="line", magic_name="cellmonitor" ) @@ -905,20 +910,23 @@ def _unload_ext(ip): fake_ext.create_session_poller = lambda client, **kw: ( # type: ignore[attr-defined] poller_created.append(client) or _FakePoller(client, **kw) ) + fake_ext.__spec__ = types.SimpleNamespace( # type: ignore[attr-defined] + name=fake_ext.__name__, _initializing=False + ) ip = InteractiveShell.instance() self.addCleanup(InteractiveShell.clear_instance) self.addCleanup(_ipython._SHELL_STATES.clear) _ipython._SHELL_STATES.clear() ip.magics_manager.magics.get("line", {}).pop("cellmonitor", None) - - spec = types.SimpleNamespace( - name=fake_ext.__name__, _initializing=False + ip.extension_manager.loaded.discard( + _cell_monitoring._CELL_MONITOR_EXTENSION ) - fake_ext.__spec__ = spec # type: ignore[attr-defined] + return ip, fake_ext, loaded, unloaded, poller_created - stdout_buf = io.StringIO() - with ( + @staticmethod + def _patch_cellmonitor_env(ip, fake_ext, stdout_buf): + return ( mock.patch.dict( sys.modules, { @@ -932,8 +940,21 @@ def _unload_ext(ip): ), mock.patch("IPython.get_ipython", return_value=ip), mock.patch("sys.stdout", stdout_buf), - ): + ) + + def test_ipython_extras_loads_and_unloads_cellmonitor_extension(self): + from google.cloud.managed_spark_connect import _ipython + + ip, fake_ext, loaded, unloaded, poller_created = ( + self._setup_fake_cellmonitor_shell() + ) + stdout_buf = io.StringIO() + p_mods, p_get_ip, p_stdout = self._patch_cellmonitor_env( + ip, fake_ext, stdout_buf + ) + with p_mods, p_get_ip, p_stdout: _ipython._init_extras() + self.assertEqual(loaded, [ip]) self.assertIn("%cellmonitor", stdout_buf.getvalue()) self.assertIn("cellmonitor", ip.magics_manager.magics["line"]) @@ -946,6 +967,116 @@ def _unload_ext(ip): self.assertFalse(bridge.begin_operation("op-after-disable")) self.assertEqual(poller_created, []) + # Re-enabling extras reloads the extension and restores %cellmonitor. + _ipython._get_or_create_config(ip).enable_extras = True + self.assertEqual(loaded, [ip, ip]) + self.assertIn("cellmonitor", ip.magics_manager.magics["line"]) + + def test_ipython_extras_loads_hooks_when_cellmonitor_magic_preexists(self): + from google.cloud.managed_spark_connect import _ipython + + ip, fake_ext, loaded, unloaded, _ = self._setup_fake_cellmonitor_shell() + + def preexisting_cellmonitor(line=""): + return f"classic:{line}" + + ip.register_magic_function( + preexisting_cellmonitor, magic_kind="line", magic_name="cellmonitor" + ) + registered_fn = ip.magics_manager.magics["line"]["cellmonitor"] + + stdout_buf = io.StringIO() + p_mods, p_get_ip, p_stdout = self._patch_cellmonitor_env( + ip, fake_ext, stdout_buf + ) + with p_mods, p_get_ip, p_stdout: + _ipython._init_extras() + # Extension still loads to attach hooks, while preserving the magic. + self.assertEqual(loaded, [ip]) + self.assertNotIn("%cellmonitor", stdout_buf.getvalue()) + self.assertIs( + ip.magics_manager.magics["line"]["cellmonitor"], registered_fn + ) + + _ipython._get_or_create_config(ip).enable_extras = False + self.assertEqual(unloaded, [ip]) + self.assertIs( + ip.magics_manager.magics["line"]["cellmonitor"], registered_fn + ) + + _ipython._get_or_create_config(ip).enable_extras = True + self.assertEqual(loaded, [ip, ip]) + self.assertIs( + ip.magics_manager.magics["line"]["cellmonitor"], registered_fn + ) + + def test_ipython_extras_reloads_after_user_overwrites_cellmonitor_magic( + self, + ): + from google.cloud.managed_spark_connect import _ipython + + ip, fake_ext, loaded, unloaded, _ = self._setup_fake_cellmonitor_shell() + stdout_buf = io.StringIO() + p_mods, p_get_ip, p_stdout = self._patch_cellmonitor_env( + ip, fake_ext, stdout_buf + ) + with p_mods, p_get_ip, p_stdout: + _ipython._init_extras() + self.assertEqual(loaded, [ip]) + + def custom_cellmonitor(line=""): + return f"custom:{line}" + + ip.register_magic_function( + custom_cellmonitor, magic_kind="line", magic_name="cellmonitor" + ) + custom_fn = ip.magics_manager.magics["line"]["cellmonitor"] + + _ipython._get_or_create_config(ip).enable_extras = False + self.assertEqual(unloaded, [ip]) + self.assertIs( + ip.magics_manager.magics["line"]["cellmonitor"], custom_fn + ) + + _ipython._get_or_create_config(ip).enable_extras = True + self.assertEqual(loaded, [ip, ip]) + self.assertIs( + ip.magics_manager.magics["line"]["cellmonitor"], custom_fn + ) + + def test_ipython_extras_preserves_preloaded_cellmonitor_extension(self): + from google.cloud.managed_spark_connect import _ipython + + ip, fake_ext, loaded, unloaded, poller_created = ( + self._setup_fake_cellmonitor_shell() + ) + stdout_buf = io.StringIO() + p_mods, p_get_ip, p_stdout = self._patch_cellmonitor_env( + ip, fake_ext, stdout_buf + ) + with p_mods, p_get_ip, p_stdout: + ip.extension_manager.load_extension( + _cell_monitoring._CELL_MONITOR_EXTENSION + ) + self.assertEqual(loaded, [ip]) + + _ipython._init_extras() + self.assertEqual(loaded, [ip]) + self.assertNotIn("%cellmonitor", stdout_buf.getvalue()) + + _ipython._get_or_create_config(ip).enable_extras = False + self.assertEqual(unloaded, []) + self.assertIn( + _cell_monitoring._CELL_MONITOR_EXTENSION, + ip.extension_manager.loaded, + ) + self.assertIn("cellmonitor", ip.magics_manager.magics["line"]) + + client = mock.MagicMock() + bridge = _cell_monitoring.SessionCellMonitorBridge(client) + self.assertTrue(bridge.begin_operation("op-preloaded")) + self.assertEqual(poller_created, [client]) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/test_init.py b/tests/unit/test_init.py index 05959600..ee22f6db 100644 --- a/tests/unit/test_init.py +++ b/tests/unit/test_init.py @@ -293,6 +293,20 @@ def test_managed_spark_magics_available(self): self.assertTrue(callable(magics_ext.load_ipython_extension)) self.assertTrue(callable(magics_ext.unload_ipython_extension)) + def test_managed_spark_cell_monitoring_available(self): + import importlib.metadata + from packaging.version import Version + import managed_spark_cell_monitoring.spark_connect as cell_mon_ext + + self.assertTrue(callable(cell_mon_ext.load_ipython_extension)) + self.assertTrue(callable(cell_mon_ext.unload_ipython_extension)) + self.assertTrue(callable(cell_mon_ext.create_session_poller)) + version = Version( + importlib.metadata.version("managed-spark-cell-monitoring") + ) + self.assertGreaterEqual(version, Version("1.1.0")) + self.assertLess(version, Version("2.0")) + def test_pyink_requirement_matches_workflow(self): """requirements-dev.txt and pyink.yaml must pin the same pyink version.""" import pathlib @@ -837,7 +851,7 @@ def test_module_import_calls_init_extras(self): def _pop_our_magics(ip): - for kind, name in _OUR_MAGICS: + for kind, name in (*_OUR_MAGICS, ("line", "cellmonitor")): ip.magics_manager.magics.get(kind, {}).pop(name, None) @@ -849,19 +863,15 @@ def _assert_magics(self, present): with self.subTest(kind=kind, name=name): self.assertEqual(name in magics[kind], present) - def setUp(self): - import os - from IPython.core.interactiveshell import InteractiveShell - from google.cloud.managed_spark_connect import _ipython - - env_patcher = mock.patch.dict(os.environ) - env_patcher.start() - self.addCleanup(env_patcher.stop) - os.environ.pop(_ipython.ENV_ENABLE_EXTRAS, None) - _ipython._SHELL_STATES.clear() - - self.ip = InteractiveShell.instance() + def _reset_shell_extras(self): self.ip.user_ns.pop("explore_dataframe", None) + if ( + "managed_spark_cell_monitoring.spark_connect" + in self.ip.extension_manager.loaded + ): + self.ip.extension_manager.unload_extension( + "managed_spark_cell_monitoring.spark_connect" + ) _pop_our_magics(self.ip) self.ip.extension_manager.loaded.discard( "google.cloud.managed_spark_magics" @@ -869,6 +879,9 @@ def setUp(self): self.ip.extension_manager.loaded.discard( "google.cloud.managed_spark_magics.sparksql" ) + self.ip.extension_manager.loaded.discard( + "managed_spark_cell_monitoring.spark_connect" + ) if "ManagedSparkConnect" in self.ip.config: del self.ip.config["ManagedSparkConnect"] self.ip.configurables[:] = [ @@ -877,6 +890,20 @@ def setUp(self): if c.__class__.__name__ != "ManagedSparkConnect" ] + def setUp(self): + import os + from IPython.core.interactiveshell import InteractiveShell + from google.cloud.managed_spark_connect import _ipython + + env_patcher = mock.patch.dict(os.environ) + env_patcher.start() + self.addCleanup(env_patcher.stop) + os.environ.pop(_ipython.ENV_ENABLE_EXTRAS, None) + _ipython._SHELL_STATES.clear() + + self.ip = InteractiveShell.instance() + self._reset_shell_extras() + self._get_ipython_patcher = mock.patch( "IPython.get_ipython", return_value=self.ip ) @@ -887,21 +914,7 @@ def tearDown(self): from google.cloud.managed_spark_connect import _ipython self._get_ipython_patcher.stop() - self.ip.user_ns.pop("explore_dataframe", None) - _pop_our_magics(self.ip) - self.ip.extension_manager.loaded.discard( - "google.cloud.managed_spark_magics" - ) - self.ip.extension_manager.loaded.discard( - "google.cloud.managed_spark_magics.sparksql" - ) - if "ManagedSparkConnect" in self.ip.config: - del self.ip.config["ManagedSparkConnect"] - self.ip.configurables[:] = [ - c - for c in self.ip.configurables - if c.__class__.__name__ != "ManagedSparkConnect" - ] + self._reset_shell_extras() InteractiveShell.clear_instance() _ipython._SHELL_STATES.clear() @@ -914,6 +927,11 @@ def test_real_shell_loads_all_extras_and_toggles_via_config(self): self.assertIn("explore_dataframe", self.ip.user_ns) self._assert_magics(present=True) + self.assertIn("cellmonitor", self.ip.magics_manager.magics["line"]) + self.assertIn( + "managed_spark_cell_monitoring.spark_connect", + self.ip.extension_manager.loaded, + ) self.ip.run_line_magic( "config", "ManagedSparkConnect.enable_extras = False" @@ -921,6 +939,11 @@ def test_real_shell_loads_all_extras_and_toggles_via_config(self): self.assertNotIn("explore_dataframe", self.ip.user_ns) self._assert_magics(present=False) + self.assertNotIn("cellmonitor", self.ip.magics_manager.magics["line"]) + self.assertNotIn( + "managed_spark_cell_monitoring.spark_connect", + self.ip.extension_manager.loaded, + ) with mock.patch("sys.stdout", io.StringIO()): self.ip.run_line_magic( @@ -929,6 +952,11 @@ def test_real_shell_loads_all_extras_and_toggles_via_config(self): self.assertIn("explore_dataframe", self.ip.user_ns) self._assert_magics(present=True) + self.assertIn("cellmonitor", self.ip.magics_manager.magics["line"]) + self.assertIn( + "managed_spark_cell_monitoring.spark_connect", + self.ip.extension_manager.loaded, + ) def test_real_shell_config_magic_pre_and_post_import(self): import io @@ -1141,12 +1169,21 @@ def test_real_shell_env_opt_out_then_enable_via_config_magic(self): import google.cloud.managed_spark_magics elif sys.argv[1] == "load_ext_first": ip.run_line_magic("load_ext", "google.cloud.managed_spark_magics") + elif sys.argv[1] == "cellmonitor_load_ext_first": + ip.run_line_magic( + "load_ext", "managed_spark_cell_monitoring.spark_connect" + ) import google.cloud.managed_spark_connect print("explore_dataframe" in ip.user_ns) print("dpip" in ip.magics_manager.magics["line"]) print("sparksql" in ip.magics_manager.magics["line"]) print("sparksql" in ip.magics_manager.magics["cell"]) +print("cellmonitor" in ip.magics_manager.magics["line"]) +print( + "managed_spark_cell_monitoring.spark_connect" + in ip.extension_manager.loaded +) """ @@ -1167,15 +1204,20 @@ def _run(self, order): return result.stdout.split() def test_all_import_orders_load_all_extras(self): - for order in ("connect_first", "magics_first", "load_ext_first"): + for order in ( + "connect_first", + "magics_first", + "load_ext_first", + "cellmonitor_load_ext_first", + ): with self.subTest(order=order): # Importing managed_spark_magics first used to re-enter # _init_extras() while that module was still initializing, # which silently dropped %dpip. self.assertEqual( self._run(order), - ["True", "True", "True", "True"], - "expected explore_dataframe, %dpip and %%sparksql", + ["True", "True", "True", "True", "True", "True"], + "expected explore_dataframe, %dpip, %%sparksql, and %cellmonitor", ) @@ -1187,6 +1229,9 @@ def test_all_import_orders_load_all_extras(self): # importlib.util.find_spec() and import treat the module as absent. for name in ( "IPython", + "anywidget", + "ipykernel", + "managed_spark_cell_monitoring", "sqlparse", "traitlets", "google.colabsqlviz",