diff --git a/pyproject.toml b/pyproject.toml index 6e0a1a7ca..c50becd7b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -287,6 +287,8 @@ test = [ # dependencies used for running tests "mypy", "gcovr; sys_platform != 'win32' or platform_machine != 'ARM64'", "gcsfs; sys_platform != 'win32' or platform_machine != 'ARM64'", + "ipykernel", + "ipywidgets", "packaging", "polars>=1.33.0", "psutil", diff --git a/src/jupyter/jupyter_progress_bar_display.cpp b/src/jupyter/jupyter_progress_bar_display.cpp index 54df7087f..fac7e836c 100644 --- a/src/jupyter/jupyter_progress_bar_display.cpp +++ b/src/jupyter/jupyter_progress_bar_display.cpp @@ -15,7 +15,7 @@ void JupyterProgressBarDisplay::Initialize() { // Initialize the progress bar nb::dict style; style["bar_color"] = "black"; - progress_bar = float_progress_attr((nb::arg("min") = 0, nb::arg("max") = 100, nb::arg("style") = style)); + progress_bar = float_progress_attr(nb::arg("min") = 0, nb::arg("max") = 100, nb::arg("style") = style); progress_bar.attr("layout").attr("width") = "auto"; @@ -31,11 +31,19 @@ JupyterProgressBarDisplay::JupyterProgressBarDisplay() : ProgressBarDisplay() { void JupyterProgressBarDisplay::Update(double progress) { nb::gil_scoped_acquire gil; - if (progress_bar.ptr() == nullptr) { - // First print, we first need to initialize the display - Initialize(); + try { + if (progress_bar.ptr() == nullptr) { + // First print, we first need to initialize the display + Initialize(); + } + progress_bar.attr("value") = nb::cast(progress); + } catch (nb::python_error &error) { + if (!error.matches(PyExc_KeyboardInterrupt)) { + throw; + } + // Raising here consumed the signal; set it again so the query's own interrupt check stops the query + PyErr_SetInterrupt(); } - progress_bar.attr("value") = nb::cast(progress); } void JupyterProgressBarDisplay::Finish() { diff --git a/tests/fast/api/test_jupyter_progress_bar.py b/tests/fast/api/test_jupyter_progress_bar.py new file mode 100644 index 000000000..27d75edcd --- /dev/null +++ b/tests/fast/api/test_jupyter_progress_bar.py @@ -0,0 +1,462 @@ +import contextlib +import json +import os +import queue +import signal +import subprocess +import sys +import time +from dataclasses import dataclass, field + +import pytest + +pytest.importorskip("ipykernel") +pytest.importorskip("ipywidgets") +jupyter_client = pytest.importorskip("jupyter_client") + +# Long enough for the engine to report progress between its tasks, short enough to finish in a fraction of a second +QUERY = "SELECT sum(a.range * b.range) FROM range(1000000) a, range(4) b" +# The aggregate reports progress before the outer projection raises +FAILING_QUERY = ( + "SELECT CASE WHEN s > 0 THEN error('stopped midway') END " + "FROM (SELECT sum(a.range * b.range) AS s FROM range(1000000) a, range(4) b)" +) +DEADLINE = 60 +# A slow runner can spend most of the deadline on the cells and must still get the time to exit cleanly +SHUTDOWN_GRACE = 15 +# A kernel that crashes stops at once instead of writing a core file first +LAUNCH_KERNEL = ( + ["-m", "ipykernel_launcher"] + if os.name == "nt" + else [ + "-c", + "import resource; resource.setrlimit(resource.RLIMIT_CORE, (0, 0)); " + "from ipykernel import kernelapp; kernelapp.launch_new_instance()", + ] +) + +IMPORT_DUCKDB = """ +import json +import duckdb +import ipywidgets +""" + + +@dataclass +class Cell: + code: str + reply: dict | None = None + messages: list = field(default_factory=list) + + def stdout(self): + return "".join( + m["content"]["text"] + for m in self.messages + if m["msg_type"] == "stream" and m["content"]["name"] == "stdout" + ) + + def errors(self): + return [m["content"] for m in self.messages if m["msg_type"] == "error"] + + def widgets(self): + return progress_widgets(self.messages) + + +@dataclass +class Kernel: + cells: list + returncode: int | None + stderr: str + + def messages(self): + return [m for cell in self.cells for m in cell.messages] + + def widgets(self): + return progress_widgets(self.messages()) + + +def progress_widgets(messages): + """The FloatProgress widgets the messages open, in order, each with its opening state and its value updates. + + The first value a statement's display sets is 0.0, the widget's initial value, which sends no update; how many + updates follow before a statement ends early depends on the machine's timing. + """ + widgets = {} + for message in messages: + content = message["content"] + if message["msg_type"] == "comm_open" and content["data"]["state"]["_model_name"] == "FloatProgressModel": + widgets[content["comm_id"]] = {"id": content["comm_id"], "state": content["data"]["state"], "values": []} + elif message["msg_type"] == "comm_msg" and content["comm_id"] in widgets: + state = content["data"]["state"] + if "value" in state: + widgets[content["comm_id"]]["values"].append(state["value"]) + return list(widgets.values()) + + +def run_kernel(tmp_path, cells, *, env=None): + """Runs the cells in a new ipykernel and ends it with a shutdown request.""" + connection_file = tmp_path / "kernel.json" + # The kernel picks free ports itself and writes them to the connection file, so parallel kernels cannot collide + child_env = { + **os.environ, + "IPYTHONDIR": str(tmp_path / "ipython"), + "JUPYTER_CONFIG_DIR": str(tmp_path / "jupyter"), + "JUPYTER_DATA_DIR": str(tmp_path / "jupyter"), + "JUPYTER_RUNTIME_DIR": str(tmp_path / "jupyter"), + "JUPYTER_PLATFORM_DIRS": "1", + "PYDEVD_DISABLE_FILE_VALIDATION": "1", + # A verbose rebuild of an editable install on import streams to sys.stderr, which in a kernel has no fileno + "SKBUILD_EDITABLE_VERBOSE": "0", + **(env or {}), + } + profile = tmp_path / "ipython" / "profile_default" + profile.mkdir(parents=True) + # The C level stderr stays the file's, so a fatal error of the interpreter reaches it + config = {"IPKernelApp": {"capture_fd_output": False}, "HistoryManager": {"enabled": False}} + (profile / "ipython_kernel_config.json").write_text(json.dumps(config)) + stderr_path = tmp_path / "stderr.txt" + deadline = time.monotonic() + DEADLINE + with stderr_path.open("w") as stderr, (tmp_path / "stdout.txt").open("w") as stdout: + process = subprocess.Popen( + [sys.executable, *LAUNCH_KERNEL, "-f", str(connection_file)], + stdin=subprocess.DEVNULL, + stdout=stdout, + stderr=stderr, + cwd=tmp_path, + env=child_env, + start_new_session=os.name != "nt", + ) + client = None + done = [] + try: + client = _connect(process, connection_file, deadline) + for code in cells: + cell = Cell(code) + done.append(cell) + if not _execute(client, process, cell, deadline): + break + if process.poll() is None: + client.shutdown() + with contextlib.suppress(subprocess.TimeoutExpired): + process.wait(timeout=max(SHUTDOWN_GRACE, deadline - time.monotonic())) + finally: + if client is not None: + client.stop_channels() + _stop(process) + return Kernel(done, process.returncode, stderr_path.read_text()) + + +def _connect(process, connection_file, deadline): + while True: + try: + info = json.loads(connection_file.read_text()) + break + except (FileNotFoundError, json.JSONDecodeError): + if process.poll() is not None or time.monotonic() > deadline: + pytest.fail("the kernel did not start") + time.sleep(0.05) + client = jupyter_client.BlockingKernelClient() + client.load_connection_info(info) + client.start_channels() + try: + client.wait_for_ready(timeout=max(1.0, deadline - time.monotonic())) + except BaseException: + client.stop_channels() + raise + return client + + +def _execute(client, process, cell, deadline): + msg_id = client.execute(cell.code, store_history=False) + idle = False + while not idle: + message = _next(client.get_iopub_msg, process, deadline) + if message is None: + return False + if message["parent_header"].get("msg_id") != msg_id: + continue + if message["msg_type"] == "status": + idle = message["content"]["execution_state"] == "idle" + else: + cell.messages.append(message) + while cell.reply is None: + message = _next(client.get_shell_msg, process, deadline) + if message is None: + return False + if message["parent_header"].get("msg_id") == msg_id: + cell.reply = message["content"] + return True + + +def _next(get, process, deadline): + while time.monotonic() < deadline and process.poll() is None: + with contextlib.suppress(queue.Empty): + return get(timeout=0.1) + return None + + +def _stop(process): + if process.poll() is not None: + return + if os.name == "nt": + process.terminate() + else: + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=10) + + +def assert_alive(kernel): + assert "Fatal Python error" not in kernel.stderr, kernel.stderr + for cell in kernel.cells: + assert cell.reply is not None, (cell.code, kernel.returncode, kernel.stderr) + + +def assert_ends_at_100(widget): + values = widget["values"] + assert values, widget + assert values == sorted(values), values + assert values[-1] == 100 + + +@pytest.mark.timeout(120) +def test_the_widget_is_made_with_its_range_and_style(tmp_path): + kernel = run_kernel( + tmp_path, + [ + IMPORT_DUCKDB + + """ +made = [] + +class Recorded(ipywidgets.FloatProgress): + def __init__(self, *args, **kwargs): + made.append([args, kwargs]) + super().__init__(*args, **kwargs) + +ipywidgets.FloatProgress = Recorded +con = duckdb.connect() +con.execute("SET progress_bar_time = 0") +""", + f""" +made.clear() +con.execute("{QUERY}").fetchall() +print(json.dumps(made)) +""", + ], + ) + assert_alive(kernel) + cell = kernel.cells[1] + assert json.loads(cell.stdout()) == [[[], {"min": 0, "max": 100, "style": {"bar_color": "black"}}]] + + opened = { + m["content"]["comm_id"]: m["content"]["data"]["state"] for m in cell.messages if m["msg_type"] == "comm_open" + } + updates = [m["content"] for m in cell.messages if m["msg_type"] == "comm_msg"] + [widget] = cell.widgets() + state = widget["state"] + assert (state["min"], state["max"]) == (0, 100) + style = opened[state["style"].removeprefix("IPY_MODEL_")] + assert (style["_model_name"], style["bar_color"]) == ("ProgressStyleModel", "black") + layout_id = state["layout"].removeprefix("IPY_MODEL_") + assert {"comm_id": layout_id, "state": {"width": "auto"}} in [ + {"comm_id": update["comm_id"], "state": update["data"]["state"]} for update in updates + ] + shown = [m["content"]["data"] for m in cell.messages if m["msg_type"] == "display_data"] + assert [view["application/vnd.jupyter.widget-view+json"]["model_id"] for view in shown] == [widget["id"]] + assert_ends_at_100(widget) + + +@pytest.mark.timeout(120) +def test_each_statement_gets_a_widget_that_ends_at_100(tmp_path): + kernel = run_kernel( + tmp_path, + [ + IMPORT_DUCKDB + + """ +con = duckdb.connect() +con.execute("SET progress_bar_time = 0") +""", + f""" +for _ in range(3): + con.execute("{QUERY}").fetchall() +""", + f'con.execute("{QUERY}; {QUERY}").fetchall()', + f'con.sql("{QUERY}").fetchall()', + ], + ) + assert_alive(kernel) + assert [len(cell.widgets()) for cell in kernel.cells[1:]] == [3, 2, 1] + for widget in kernel.widgets(): + assert_ends_at_100(widget) + + +@pytest.mark.timeout(120) +def test_a_query_that_fails_midway_keeps_the_kernel(tmp_path): + kernel = run_kernel( + tmp_path, + [ + IMPORT_DUCKDB + + """ +con = duckdb.connect() +con.execute("SET progress_bar_time = 0") +""", + f'con.execute("{FAILING_QUERY}").fetchall()', + f'con.execute("{QUERY}").fetchall()', + ], + ) + assert_alive(kernel) + failed, after = kernel.cells[1:] + [error] = failed.errors() + assert error["ename"] == "InvalidInputException" + assert "stopped midway" in error["evalue"] + assert len(failed.widgets()) == 1 + assert not after.errors() + [widget] = after.widgets() + assert_ends_at_100(widget) + + +@pytest.mark.timeout(120) +def test_an_interrupt_while_the_widget_shows_interrupts_the_query(tmp_path): + kernel = run_kernel( + tmp_path, + [ + IMPORT_DUCKDB + + """ +import _thread +import threading + +con = duckdb.connect(config={"threads": 2}) +con.execute("SET progress_bar_time = 0") +""", + """ +threading.Timer(0.5, _thread.interrupt_main).start() +try: + con.execute("SELECT sum(a.range * b.range) FROM range(100000000) a, range(4) b").fetchall() + print("finished") +except BaseException as error: + print(type(error).__name__, error) +""", + ], + ) + assert_alive(kernel) + assert kernel.cells[1].stdout() == "RuntimeError Query interrupted\n" + assert len(kernel.cells[1].widgets()) == 1 + + +@pytest.mark.timeout(120) +def test_an_interrupt_raised_inside_the_widget_interrupts_the_query(tmp_path): + # The signal arrives inside the widget's first update, whatever the timing, so the client's own check sees it next + kernel = run_kernel( + tmp_path, + [ + IMPORT_DUCKDB + + """ +import signal + +armed = [] + +class Interrupting(ipywidgets.FloatProgress): + def __setattr__(self, name, value): + if name == "value" and armed: + armed.clear() + signal.raise_signal(signal.SIGINT) + super().__setattr__(name, value) + +ipywidgets.FloatProgress = Interrupting +con = duckdb.connect() +con.execute("SET progress_bar_time = 0") +armed.append(True) +try: + con.execute("SELECT sum(a.range * b.range) FROM range(100000000) a, range(4) b").fetchall() + print("finished") +except BaseException as error: + print(type(error).__name__, error) +""", + ], + ) + assert_alive(kernel) + assert kernel.cells[0].stdout() == "RuntimeError Query interrupted\n" + + +@pytest.mark.timeout(120) +@pytest.mark.parametrize( + ("widget", "message"), + [ + pytest.param( + """ +class Broken(ipywidgets.FloatProgress): + def __init__(self, *args, **kwargs): + raise RuntimeError("the widget cannot be made") +""", + "RuntimeError: the widget cannot be made", + id="creation", + ), + pytest.param( + """ +class Broken: + def __init__(self, **kwargs): + pass +""", + "AttributeError: 'Broken' object has no attribute 'layout'", + id="missing-attribute", + ), + pytest.param( + """ +class Broken(ipywidgets.FloatProgress): + def __setattr__(self, name, value): + if name == "value": + raise RuntimeError("the update is refused") + super().__setattr__(name, value) +""", + "RuntimeError: the update is refused", + id="update", + ), + ], +) +def test_a_widget_that_raises_fails_the_statement(tmp_path, widget, message): + kernel = run_kernel( + tmp_path, + [ + IMPORT_DUCKDB + widget + "ipywidgets.FloatProgress = Broken\n", + f""" +con = duckdb.connect() +try: + con.execute("SET progress_bar_time = 0") + con.execute("{QUERY}").fetchall() +except duckdb.Error as error: + print(type(error).__name__) + print(error) +""", + "print('alive')", + ], + ) + assert_alive(kernel) + raised = kernel.cells[1].stdout() + assert raised.startswith("Error\n"), raised + assert message in raised + assert kernel.cells[2].stdout() == "alive\n" + + +@pytest.mark.timeout(120) +def test_the_kernel_exits_cleanly_after_showing_bars(tmp_path): + kernel = run_kernel( + tmp_path, + [ + IMPORT_DUCKDB + + """ +con = duckdb.connect() +con.execute("SET progress_bar_time = 0") +""", + f""" +for _ in range(3): + con.execute("{QUERY}").fetchall() +""", + ], + env={"PYTHONMALLOC": "debug"}, + ) + assert_alive(kernel) + assert len(kernel.cells[1].widgets()) == 3 + assert kernel.returncode == 0, kernel.stderr