Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions DEVELOPING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down
13 changes: 6 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]'
Expand Down Expand Up @@ -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
Expand Down
31 changes: 22 additions & 9 deletions google/cloud/managed_spark_connect/_ipython.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
),
)

Expand Down Expand Up @@ -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(
Expand All @@ -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:
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand All @@ -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):
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
149 changes: 140 additions & 9 deletions tests/unit/test_cell_monitoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand All @@ -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,
{
Expand All @@ -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"])

Expand All @@ -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()
Loading
Loading