From be48f55d315f58ef01b0d54af9a5f8bccad89841 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Wed, 2 Dec 2026 18:02:25 +0000 Subject: [PATCH 1/4] Give a cursor the Jupyter progress bar and release its widget under the GIL --- pyproject.toml | 1 + .../jupyter_progress_bar_display.hpp | 5 +- src/jupyter/jupyter_progress_bar_display.cpp | 23 +- src/pyconnection.cpp | 3 + tests/fast/api/test_jupyter_progress_bar.py | 502 ++++++++++++++++++ tests/fast/api/test_query_progress.py | 6 +- 6 files changed, 527 insertions(+), 13 deletions(-) create mode 100644 tests/fast/api/test_jupyter_progress_bar.py diff --git a/pyproject.toml b/pyproject.toml index 6e0a1a7ca..3e32cbf4d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -287,6 +287,7 @@ test = [ # dependencies used for running tests "mypy", "gcovr; sys_platform != 'win32' or platform_machine != 'ARM64'", "gcsfs; sys_platform != 'win32' or platform_machine != 'ARM64'", + "ipykernel", "packaging", "polars>=1.33.0", "psutil", diff --git a/src/include/duckdb_python/jupyter_progress_bar_display.hpp b/src/include/duckdb_python/jupyter_progress_bar_display.hpp index f771cf9a3..2daa0c39a 100644 --- a/src/include/duckdb_python/jupyter_progress_bar_display.hpp +++ b/src/include/duckdb_python/jupyter_progress_bar_display.hpp @@ -8,7 +8,7 @@ #pragma once -#include "duckdb_python/nb/casters.hpp" +#include "duckdb_python/registered_py_object.hpp" #include "duckdb/common/progress_bar/progress_bar_display.hpp" #include "duckdb/common/helper.hpp" @@ -30,7 +30,8 @@ class JupyterProgressBarDisplay : public ProgressBarDisplay { void Initialize(); private: - nb::object progress_bar; + //! The engine destroys the display at the end of a statement, on a thread that may not hold the GIL + unique_ptr progress_bar; }; } // namespace duckdb diff --git a/src/jupyter/jupyter_progress_bar_display.cpp b/src/jupyter/jupyter_progress_bar_display.cpp index 54df7087f..a98c16da7 100644 --- a/src/jupyter/jupyter_progress_bar_display.cpp +++ b/src/jupyter/jupyter_progress_bar_display.cpp @@ -1,5 +1,7 @@ #include "duckdb_python/jupyter_progress_bar_display.hpp" +#include "duckdb_python/exceptions.hpp" #include "duckdb_python/pyconnection/pyconnection.hpp" +#include "duckdb_python/pyutil.hpp" #include "duckdb_python/nb/casters.hpp" namespace duckdb { @@ -15,14 +17,15 @@ 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 = make_uniq( + float_progress_attr(nb::arg("min") = 0, nb::arg("max") = 100, nb::arg("style") = style)); - progress_bar.attr("layout").attr("width") = "auto"; + progress_bar->obj.attr("layout").attr("width") = "auto"; // Display the progress bar auto display_attr = import_cache.IPython.display.display(); D_ASSERT(display_attr.ptr() != nullptr); - display_attr(progress_bar); + display_attr(progress_bar->obj); } JupyterProgressBarDisplay::JupyterProgressBarDisplay() : ProgressBarDisplay() { @@ -30,12 +33,16 @@ 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(); + PyUtil::QueryGil gil(nullptr); + try { + if (!progress_bar) { + // First print, we first need to initialize the display + Initialize(); + } + progress_bar->obj.attr("value") = nb::cast(progress); + } catch (nb::python_error &error) { + throw AsDuckDBError(error); } - progress_bar.attr("value") = nb::cast(progress); } void JupyterProgressBarDisplay::Finish() { diff --git a/src/pyconnection.cpp b/src/pyconnection.cpp index 49960d552..88ed862eb 100644 --- a/src/pyconnection.cpp +++ b/src/pyconnection.cpp @@ -1459,10 +1459,13 @@ void DuckDBPyConnection::Cursors::ClearCursors() { cursors.clear(); } +static void SetDefaultConfigArguments(ClientContext &context); + std::shared_ptr DuckDBPyConnection::Cursor() { auto res = std::make_shared(); res->con.SetDatabase(con); res->con.SetConnection(make_uniq(res->con.GetDatabase())); + SetDefaultConfigArguments(*res->con.GetConnection().context); cursors.AddCursor(res); return res; } 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..0be4075d2 --- /dev/null +++ b/tests/fast/api/test_jupyter_progress_bar.py @@ -0,0 +1,502 @@ +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 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.""" + 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, *, interpreter_args=(), env=None, stop="shutdown"): + """Runs the cells in a new ipykernel and ends it: with a shutdown request, or with stop="exit" from a last cell.""" + 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, *interpreter_args, *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: + if stop == "exit": + # The control thread's shutdown handler fails when asyncio runs in debug mode, as under -X dev + client.execute("get_ipython().ask_exit()", store_history=False) + else: + client.shutdown() + with contextlib.suppress(subprocess.TimeoutExpired): + process.wait(timeout=max(1.0, 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 +""", + f""" +con = duckdb.connect() +con.execute("SET progress_bar_time = 0") +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_a_cursor_shows_the_widget_as_its_connection_does(tmp_path): + kernel = run_kernel( + tmp_path, + [ + IMPORT_DUCKDB, + """ +con = duckdb.connect() +parent = con.cursor() +cursors = [con, parent, parent.cursor(), duckdb.cursor()] +print(json.dumps([c.execute("SELECT current_setting('enable_progress_bar')").fetchone()[0] for c in cursors])) +for c in cursors: + c.execute("SET progress_bar_time = 0") +""", + *(f'cursors[{i}].execute("{QUERY}").fetchall()' for i in range(4)), + ], + ) + assert_alive(kernel) + assert json.loads(kernel.cells[1].stdout()) == [True, True, True, True] + for cell in kernel.cells[2:]: + [widget] = cell.widgets() + assert_ends_at_100(widget) + + +@pytest.mark.timeout(120) +def test_a_cursor_in_a_kernel_without_ipywidgets_refuses_the_bar_as_its_connection_does(tmp_path): + kernel = run_kernel( + tmp_path, + [ + """ +import json +import sys +sys.modules["ipywidgets"] = None +import duckdb + +con = duckdb.connect() +refused = [] +for c in (con, con.cursor(), duckdb.cursor()): + enabled = c.execute("SELECT current_setting('enable_progress_bar')").fetchone()[0] + try: + c.execute("SET progress_bar_time = 0") + refused.append([enabled, None]) + except duckdb.InvalidInputException as error: + refused.append([enabled, str(error)]) +print(json.dumps(refused)) +""", + ], + ) + assert_alive(kernel) + reported = json.loads(kernel.cells[0].stdout()) + assert [enabled for enabled, _ in reported] == [False, False, False] + for _, message in reported: + assert "required package 'ipywidgets' is missing" in message + + +@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() +first, second = con.cursor(), con.cursor() +for c in (con, first, second): + c.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()', + f""" +for c in (first, second, first, second): + c.execute("{QUERY}").fetchall() +""", + ], + ) + assert_alive(kernel) + assert [len(cell.widgets()) for cell in kernel.cells[1:]] == [3, 2, 1, 4] + 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"] + [shown] = failed.widgets() + assert shown["values"] + assert not after.errors() + [widget] = after.widgets() + assert_ends_at_100(widget) + + +@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() +con.execute("SET progress_bar_time = 0") +try: + 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_last_reference_to_the_widget_is_released_safely(tmp_path): + # A closed widget leaves the ipywidgets registry and its comm, so the display holds its last reference and frees it + kernel = run_kernel( + tmp_path, + [ + IMPORT_DUCKDB + + """ +freed = [] + +class Closed(ipywidgets.FloatProgress): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.close() + + def __del__(self): + freed.append(self.value) + super().__del__() + +ipywidgets.FloatProgress = Closed +con = duckdb.connect() +cur = con.cursor() +for c in (con, cur): + c.execute("SET progress_bar_time = 0") +""", + f""" +con.execute("{QUERY}").fetchall() +try: + con.execute("{FAILING_QUERY}").fetchall() +except duckdb.InvalidInputException: + pass +cur.execute("{QUERY}").fetchall() +print(json.dumps(freed)) +""", + ], + interpreter_args=("-X", "dev"), + env={"PYTHONMALLOC": "debug"}, + stop="exit", + ) + assert_alive(kernel) + freed = json.loads(kernel.cells[1].stdout()) + assert len(freed) == 3 + assert freed[0] == freed[2] == 100 + assert kernel.returncode == 0, kernel.stderr + + +@pytest.mark.timeout(120) +def test_the_kernel_exits_cleanly_after_showing_bars(tmp_path): + kernel = run_kernel( + tmp_path, + [ + IMPORT_DUCKDB + + f""" +con = duckdb.connect() +for c in (con, con.cursor(), duckdb.cursor()): + c.execute("SET progress_bar_time = 0") + c.execute("{QUERY}").fetchall() +""", + ], + env={"PYTHONMALLOC": "debug"}, + ) + assert_alive(kernel) + assert len(kernel.widgets()) == 3 + assert kernel.returncode == 0, kernel.stderr diff --git a/tests/fast/api/test_query_progress.py b/tests/fast/api/test_query_progress.py index 2db3726b9..bd4dc8c50 100644 --- a/tests/fast/api/test_query_progress.py +++ b/tests/fast/api/test_query_progress.py @@ -122,13 +122,13 @@ def _reported(stdout: str) -> list[str]: def test_an_interactive_session_enables_the_progress_bar(tmp_path): # The client treats a __main__ without __file__ as an interactive session, so a child run from -c is one and a - # child run from a script is not. The value is the session's own: a cursor, which gets no default, reads the - # engine's default, and a RESET returns to it. + # child run from a script is not. The value is the session's own: a cursor gets the default as its connection + # does, and a RESET returns to the engine's default. interactive = subprocess.run( [sys.executable, "-c", _READ_AND_SET], capture_output=True, text=True, timeout=60, check=False ) assert interactive.returncode == 0, interactive.stderr - assert _reported(interactive.stdout) == ["enabled True", "cursor False", "after set False", "after reset False"] + assert _reported(interactive.stdout) == ["enabled True", "cursor True", "after set False", "after reset False"] script = tmp_path / "script.py" script.write_text(_READ_AND_SET) From 77d524dfecc68efd5555c34699dc63ef0a8424e5 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Wed, 2 Dec 2026 19:35:26 +0000 Subject: [PATCH 2/4] Hand an interrupt met by the progress widget back to the query, and test the widget in CI --- pyproject.toml | 1 + src/jupyter/jupyter_progress_bar_display.cpp | 5 + tests/fast/api/test_jupyter_progress_bar.py | 139 +++++++++++++++++-- 3 files changed, 136 insertions(+), 9 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 3e32cbf4d..c50becd7b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -288,6 +288,7 @@ test = [ # dependencies used for running tests "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 a98c16da7..5f296f3f8 100644 --- a/src/jupyter/jupyter_progress_bar_display.cpp +++ b/src/jupyter/jupyter_progress_bar_display.cpp @@ -41,6 +41,11 @@ void JupyterProgressBarDisplay::Update(double progress) { } progress_bar->obj.attr("value") = nb::cast(progress); } catch (nb::python_error &error) { + if (error.matches(PyExc_KeyboardInterrupt)) { + // Raising here consumed the signal; set it again so the query's own interrupt check stops the query + PyErr_SetInterrupt(); + return; + } throw AsDuckDBError(error); } } diff --git a/tests/fast/api/test_jupyter_progress_bar.py b/tests/fast/api/test_jupyter_progress_bar.py index 0be4075d2..89d5dba17 100644 --- a/tests/fast/api/test_jupyter_progress_bar.py +++ b/tests/fast/api/test_jupyter_progress_bar.py @@ -302,23 +302,29 @@ def test_a_cursor_in_a_kernel_without_ipywidgets_refuses_the_bar_as_its_connecti import duckdb con = duckdb.connect() -refused = [] +reported = [] for c in (con, con.cursor(), duckdb.cursor()): enabled = c.execute("SELECT current_setting('enable_progress_bar')").fetchone()[0] - try: - c.execute("SET progress_bar_time = 0") - refused.append([enabled, None]) - except duckdb.InvalidInputException as error: - refused.append([enabled, str(error)]) -print(json.dumps(refused)) + refused = [] + for setting in ("progress_bar_time = 0", "enable_progress_bar = false", "enable_progress_bar_print = false"): + try: + c.execute(f"SET {setting}") + refused.append(None) + except duckdb.InvalidInputException as error: + refused.append(str(error)) + reported.append([enabled, refused]) +print(json.dumps(reported)) """, ], ) assert_alive(kernel) reported = json.loads(kernel.cells[0].stdout()) assert [enabled for enabled, _ in reported] == [False, False, False] - for _, message in reported: - assert "required package 'ipywidgets' is missing" in message + for _, refused in reported: + assert len(refused) == 3 + for message in refused: + assert message is not None, reported + assert "required package 'ipywidgets' is missing" in message @pytest.mark.timeout(120) @@ -377,6 +383,67 @@ def test_a_query_that_fails_midway_keeps_the_kernel(tmp_path): assert_ends_at_100(widget) +@pytest.mark.timeout(120) +@pytest.mark.parametrize("target", ["con", "con.cursor()"]) +def test_an_interrupt_while_the_widget_shows_interrupts_the_query(tmp_path, target): + kernel = run_kernel( + tmp_path, + [ + IMPORT_DUCKDB + + f""" +import _thread +import threading + +con = duckdb.connect(config={{"threads": 2}}) +c = {target} +c.execute("SET progress_bar_time = 0") +threading.Timer(0.5, _thread.interrupt_main).start() +try: + c.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" + [widget] = kernel.widgets() + assert widget["values"] + + +@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 + +class Interrupting(ipywidgets.FloatProgress): + def __setattr__(self, name, value): + if name == "value" and not getattr(self, "interrupted", False): + object.__setattr__(self, "interrupted", True) + signal.raise_signal(signal.SIGINT) + super().__setattr__(name, value) + +ipywidgets.FloatProgress = Interrupting +con = duckdb.connect() +con.execute("SET progress_bar_time = 0") +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"), @@ -500,3 +567,57 @@ def test_the_kernel_exits_cleanly_after_showing_bars(tmp_path): assert_alive(kernel) assert len(kernel.widgets()) == 3 assert kernel.returncode == 0, kernel.stderr + + +@pytest.mark.timeout(120) +@pytest.mark.parametrize("target", ["con", "con.cursor()"]) +def test_a_query_another_thread_starts_after_the_exit_hook_shows_no_widget(tmp_path, target): + outcome = tmp_path / "outcome.txt" + kernel = run_kernel( + tmp_path, + [ + # Registered before the import, so it runs after duckdb's exit hook and holds the exit open for the query + f""" +import atexit +import threading + +state = {{"go": threading.Event(), "done": threading.Event(), "made": []}} + +def after(): + state["go"].set() + finished = state["done"].wait(30) + with open({str(outcome)!r}, "w") as f: + f.write(f"{{finished}} {{len(state['made'])}} {{state.get('outcome')}}") + +atexit.register(after) +""" + + IMPORT_DUCKDB + + f""" +class Counted(ipywidgets.FloatProgress): + def __init__(self, *args, **kwargs): + state["made"].append(True) + super().__init__(*args, **kwargs) + +ipywidgets.FloatProgress = Counted +con = duckdb.connect() +con.execute("SET progress_bar_time = 0") + +def query_after_the_hook(): + state["go"].wait() + try: + state["outcome"] = {target}.execute("SET progress_bar_time = 0; {QUERY}").fetchone() + except duckdb.Error as error: + state["outcome"] = f"{{type(error).__name__}}: {{error}}" + state["done"].set() + +threading.Thread(target=query_after_the_hook, daemon=True).start() +""", + ], + ) + assert_alive(kernel) + assert kernel.returncode == 0, kernel.stderr + finished, made, message = outcome.read_text().split(" ", 2) + assert finished == "True" + assert message.startswith("InvalidInputException: "), message + assert message.endswith("the Python interpreter is shutting down"), message + assert made == "0" From b91a728ed97203de1d8a80fc86f817ffd1585a67 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Wed, 2 Dec 2026 22:00:50 +0000 Subject: [PATCH 3/4] Leave the widget's release, the display's GIL and the cursor's widget as they are on main --- .../jupyter_progress_bar_display.hpp | 5 +- src/jupyter/jupyter_progress_bar_display.cpp | 24 +- src/pyconnection.cpp | 3 - tests/fast/api/test_jupyter_progress_bar.py | 205 ++---------------- tests/fast/api/test_query_progress.py | 6 +- 5 files changed, 32 insertions(+), 211 deletions(-) diff --git a/src/include/duckdb_python/jupyter_progress_bar_display.hpp b/src/include/duckdb_python/jupyter_progress_bar_display.hpp index 2daa0c39a..f771cf9a3 100644 --- a/src/include/duckdb_python/jupyter_progress_bar_display.hpp +++ b/src/include/duckdb_python/jupyter_progress_bar_display.hpp @@ -8,7 +8,7 @@ #pragma once -#include "duckdb_python/registered_py_object.hpp" +#include "duckdb_python/nb/casters.hpp" #include "duckdb/common/progress_bar/progress_bar_display.hpp" #include "duckdb/common/helper.hpp" @@ -30,8 +30,7 @@ class JupyterProgressBarDisplay : public ProgressBarDisplay { void Initialize(); private: - //! The engine destroys the display at the end of a statement, on a thread that may not hold the GIL - unique_ptr progress_bar; + nb::object progress_bar; }; } // namespace duckdb diff --git a/src/jupyter/jupyter_progress_bar_display.cpp b/src/jupyter/jupyter_progress_bar_display.cpp index 5f296f3f8..fac7e836c 100644 --- a/src/jupyter/jupyter_progress_bar_display.cpp +++ b/src/jupyter/jupyter_progress_bar_display.cpp @@ -1,7 +1,5 @@ #include "duckdb_python/jupyter_progress_bar_display.hpp" -#include "duckdb_python/exceptions.hpp" #include "duckdb_python/pyconnection/pyconnection.hpp" -#include "duckdb_python/pyutil.hpp" #include "duckdb_python/nb/casters.hpp" namespace duckdb { @@ -17,15 +15,14 @@ void JupyterProgressBarDisplay::Initialize() { // Initialize the progress bar nb::dict style; style["bar_color"] = "black"; - progress_bar = make_uniq( - 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->obj.attr("layout").attr("width") = "auto"; + progress_bar.attr("layout").attr("width") = "auto"; // Display the progress bar auto display_attr = import_cache.IPython.display.display(); D_ASSERT(display_attr.ptr() != nullptr); - display_attr(progress_bar->obj); + display_attr(progress_bar); } JupyterProgressBarDisplay::JupyterProgressBarDisplay() : ProgressBarDisplay() { @@ -33,20 +30,19 @@ JupyterProgressBarDisplay::JupyterProgressBarDisplay() : ProgressBarDisplay() { } void JupyterProgressBarDisplay::Update(double progress) { - PyUtil::QueryGil gil(nullptr); + nb::gil_scoped_acquire gil; try { - if (!progress_bar) { + if (progress_bar.ptr() == nullptr) { // First print, we first need to initialize the display Initialize(); } - progress_bar->obj.attr("value") = nb::cast(progress); + progress_bar.attr("value") = nb::cast(progress); } catch (nb::python_error &error) { - if (error.matches(PyExc_KeyboardInterrupt)) { - // Raising here consumed the signal; set it again so the query's own interrupt check stops the query - PyErr_SetInterrupt(); - return; + if (!error.matches(PyExc_KeyboardInterrupt)) { + throw; } - throw AsDuckDBError(error); + // Raising here consumed the signal; set it again so the query's own interrupt check stops the query + PyErr_SetInterrupt(); } } diff --git a/src/pyconnection.cpp b/src/pyconnection.cpp index 88ed862eb..49960d552 100644 --- a/src/pyconnection.cpp +++ b/src/pyconnection.cpp @@ -1459,13 +1459,10 @@ void DuckDBPyConnection::Cursors::ClearCursors() { cursors.clear(); } -static void SetDefaultConfigArguments(ClientContext &context); - std::shared_ptr DuckDBPyConnection::Cursor() { auto res = std::make_shared(); res->con.SetDatabase(con); res->con.SetConnection(make_uniq(res->con.GetDatabase())); - SetDefaultConfigArguments(*res->con.GetConnection().context); cursors.AddCursor(res); return res; } diff --git a/tests/fast/api/test_jupyter_progress_bar.py b/tests/fast/api/test_jupyter_progress_bar.py index 89d5dba17..200309a37 100644 --- a/tests/fast/api/test_jupyter_progress_bar.py +++ b/tests/fast/api/test_jupyter_progress_bar.py @@ -22,6 +22,8 @@ "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"] @@ -87,8 +89,8 @@ def progress_widgets(messages): return list(widgets.values()) -def run_kernel(tmp_path, cells, *, interpreter_args=(), env=None, stop="shutdown"): - """Runs the cells in a new ipykernel and ends it: with a shutdown request, or with stop="exit" from a last cell.""" +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 = { @@ -112,7 +114,7 @@ def run_kernel(tmp_path, cells, *, interpreter_args=(), env=None, stop="shutdown deadline = time.monotonic() + DEADLINE with stderr_path.open("w") as stderr, (tmp_path / "stdout.txt").open("w") as stdout: process = subprocess.Popen( - [sys.executable, *interpreter_args, *LAUNCH_KERNEL, "-f", str(connection_file)], + [sys.executable, *LAUNCH_KERNEL, "-f", str(connection_file)], stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr, @@ -130,13 +132,9 @@ def run_kernel(tmp_path, cells, *, interpreter_args=(), env=None, stop="shutdown if not _execute(client, process, cell, deadline): break if process.poll() is None: - if stop == "exit": - # The control thread's shutdown handler fails when asyncio runs in debug mode, as under -X dev - client.execute("get_ipython().ask_exit()", store_history=False) - else: - client.shutdown() + client.shutdown() with contextlib.suppress(subprocess.TimeoutExpired): - process.wait(timeout=max(1.0, deadline - time.monotonic())) + process.wait(timeout=max(SHUTDOWN_GRACE, deadline - time.monotonic())) finally: if client is not None: client.stop_channels() @@ -266,67 +264,6 @@ def __init__(self, *args, **kwargs): assert_ends_at_100(widget) -@pytest.mark.timeout(120) -def test_a_cursor_shows_the_widget_as_its_connection_does(tmp_path): - kernel = run_kernel( - tmp_path, - [ - IMPORT_DUCKDB, - """ -con = duckdb.connect() -parent = con.cursor() -cursors = [con, parent, parent.cursor(), duckdb.cursor()] -print(json.dumps([c.execute("SELECT current_setting('enable_progress_bar')").fetchone()[0] for c in cursors])) -for c in cursors: - c.execute("SET progress_bar_time = 0") -""", - *(f'cursors[{i}].execute("{QUERY}").fetchall()' for i in range(4)), - ], - ) - assert_alive(kernel) - assert json.loads(kernel.cells[1].stdout()) == [True, True, True, True] - for cell in kernel.cells[2:]: - [widget] = cell.widgets() - assert_ends_at_100(widget) - - -@pytest.mark.timeout(120) -def test_a_cursor_in_a_kernel_without_ipywidgets_refuses_the_bar_as_its_connection_does(tmp_path): - kernel = run_kernel( - tmp_path, - [ - """ -import json -import sys -sys.modules["ipywidgets"] = None -import duckdb - -con = duckdb.connect() -reported = [] -for c in (con, con.cursor(), duckdb.cursor()): - enabled = c.execute("SELECT current_setting('enable_progress_bar')").fetchone()[0] - refused = [] - for setting in ("progress_bar_time = 0", "enable_progress_bar = false", "enable_progress_bar_print = false"): - try: - c.execute(f"SET {setting}") - refused.append(None) - except duckdb.InvalidInputException as error: - refused.append(str(error)) - reported.append([enabled, refused]) -print(json.dumps(reported)) -""", - ], - ) - assert_alive(kernel) - reported = json.loads(kernel.cells[0].stdout()) - assert [enabled for enabled, _ in reported] == [False, False, False] - for _, refused in reported: - assert len(refused) == 3 - for message in refused: - assert message is not None, reported - assert "required package 'ipywidgets' is missing" in message - - @pytest.mark.timeout(120) def test_each_statement_gets_a_widget_that_ends_at_100(tmp_path): kernel = run_kernel( @@ -335,9 +272,7 @@ def test_each_statement_gets_a_widget_that_ends_at_100(tmp_path): IMPORT_DUCKDB + """ con = duckdb.connect() -first, second = con.cursor(), con.cursor() -for c in (con, first, second): - c.execute("SET progress_bar_time = 0") +con.execute("SET progress_bar_time = 0") """, f""" for _ in range(3): @@ -345,14 +280,10 @@ def test_each_statement_gets_a_widget_that_ends_at_100(tmp_path): """, f'con.execute("{QUERY}; {QUERY}").fetchall()', f'con.sql("{QUERY}").fetchall()', - f""" -for c in (first, second, first, second): - c.execute("{QUERY}").fetchall() -""", ], ) assert_alive(kernel) - assert [len(cell.widgets()) for cell in kernel.cells[1:]] == [3, 2, 1, 4] + assert [len(cell.widgets()) for cell in kernel.cells[1:]] == [3, 2, 1] for widget in kernel.widgets(): assert_ends_at_100(widget) @@ -384,22 +315,20 @@ def test_a_query_that_fails_midway_keeps_the_kernel(tmp_path): @pytest.mark.timeout(120) -@pytest.mark.parametrize("target", ["con", "con.cursor()"]) -def test_an_interrupt_while_the_widget_shows_interrupts_the_query(tmp_path, target): +def test_an_interrupt_while_the_widget_shows_interrupts_the_query(tmp_path): kernel = run_kernel( tmp_path, [ IMPORT_DUCKDB - + f""" + + """ import _thread import threading -con = duckdb.connect(config={{"threads": 2}}) -c = {target} -c.execute("SET progress_bar_time = 0") +con = duckdb.connect(config={"threads": 2}) +con.execute("SET progress_bar_time = 0") threading.Timer(0.5, _thread.interrupt_main).start() try: - c.execute("SELECT sum(a.range * b.range) FROM range(100000000) a, range(4) b").fetchall() + 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) @@ -503,52 +432,6 @@ def test_a_widget_that_raises_fails_the_statement(tmp_path, widget, message): assert kernel.cells[2].stdout() == "alive\n" -@pytest.mark.timeout(120) -def test_the_last_reference_to_the_widget_is_released_safely(tmp_path): - # A closed widget leaves the ipywidgets registry and its comm, so the display holds its last reference and frees it - kernel = run_kernel( - tmp_path, - [ - IMPORT_DUCKDB - + """ -freed = [] - -class Closed(ipywidgets.FloatProgress): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.close() - - def __del__(self): - freed.append(self.value) - super().__del__() - -ipywidgets.FloatProgress = Closed -con = duckdb.connect() -cur = con.cursor() -for c in (con, cur): - c.execute("SET progress_bar_time = 0") -""", - f""" -con.execute("{QUERY}").fetchall() -try: - con.execute("{FAILING_QUERY}").fetchall() -except duckdb.InvalidInputException: - pass -cur.execute("{QUERY}").fetchall() -print(json.dumps(freed)) -""", - ], - interpreter_args=("-X", "dev"), - env={"PYTHONMALLOC": "debug"}, - stop="exit", - ) - assert_alive(kernel) - freed = json.loads(kernel.cells[1].stdout()) - assert len(freed) == 3 - assert freed[0] == freed[2] == 100 - assert kernel.returncode == 0, kernel.stderr - - @pytest.mark.timeout(120) def test_the_kernel_exits_cleanly_after_showing_bars(tmp_path): kernel = run_kernel( @@ -557,9 +440,9 @@ def test_the_kernel_exits_cleanly_after_showing_bars(tmp_path): IMPORT_DUCKDB + f""" con = duckdb.connect() -for c in (con, con.cursor(), duckdb.cursor()): - c.execute("SET progress_bar_time = 0") - c.execute("{QUERY}").fetchall() +con.execute("SET progress_bar_time = 0") +for _ in range(3): + con.execute("{QUERY}").fetchall() """, ], env={"PYTHONMALLOC": "debug"}, @@ -567,57 +450,3 @@ def test_the_kernel_exits_cleanly_after_showing_bars(tmp_path): assert_alive(kernel) assert len(kernel.widgets()) == 3 assert kernel.returncode == 0, kernel.stderr - - -@pytest.mark.timeout(120) -@pytest.mark.parametrize("target", ["con", "con.cursor()"]) -def test_a_query_another_thread_starts_after_the_exit_hook_shows_no_widget(tmp_path, target): - outcome = tmp_path / "outcome.txt" - kernel = run_kernel( - tmp_path, - [ - # Registered before the import, so it runs after duckdb's exit hook and holds the exit open for the query - f""" -import atexit -import threading - -state = {{"go": threading.Event(), "done": threading.Event(), "made": []}} - -def after(): - state["go"].set() - finished = state["done"].wait(30) - with open({str(outcome)!r}, "w") as f: - f.write(f"{{finished}} {{len(state['made'])}} {{state.get('outcome')}}") - -atexit.register(after) -""" - + IMPORT_DUCKDB - + f""" -class Counted(ipywidgets.FloatProgress): - def __init__(self, *args, **kwargs): - state["made"].append(True) - super().__init__(*args, **kwargs) - -ipywidgets.FloatProgress = Counted -con = duckdb.connect() -con.execute("SET progress_bar_time = 0") - -def query_after_the_hook(): - state["go"].wait() - try: - state["outcome"] = {target}.execute("SET progress_bar_time = 0; {QUERY}").fetchone() - except duckdb.Error as error: - state["outcome"] = f"{{type(error).__name__}}: {{error}}" - state["done"].set() - -threading.Thread(target=query_after_the_hook, daemon=True).start() -""", - ], - ) - assert_alive(kernel) - assert kernel.returncode == 0, kernel.stderr - finished, made, message = outcome.read_text().split(" ", 2) - assert finished == "True" - assert message.startswith("InvalidInputException: "), message - assert message.endswith("the Python interpreter is shutting down"), message - assert made == "0" diff --git a/tests/fast/api/test_query_progress.py b/tests/fast/api/test_query_progress.py index bd4dc8c50..2db3726b9 100644 --- a/tests/fast/api/test_query_progress.py +++ b/tests/fast/api/test_query_progress.py @@ -122,13 +122,13 @@ def _reported(stdout: str) -> list[str]: def test_an_interactive_session_enables_the_progress_bar(tmp_path): # The client treats a __main__ without __file__ as an interactive session, so a child run from -c is one and a - # child run from a script is not. The value is the session's own: a cursor gets the default as its connection - # does, and a RESET returns to the engine's default. + # child run from a script is not. The value is the session's own: a cursor, which gets no default, reads the + # engine's default, and a RESET returns to it. interactive = subprocess.run( [sys.executable, "-c", _READ_AND_SET], capture_output=True, text=True, timeout=60, check=False ) assert interactive.returncode == 0, interactive.stderr - assert _reported(interactive.stdout) == ["enabled True", "cursor True", "after set False", "after reset False"] + assert _reported(interactive.stdout) == ["enabled True", "cursor False", "after set False", "after reset False"] script = tmp_path / "script.py" script.write_text(_READ_AND_SET) From e612ac1bbe7243274d599a19bdc40e12779b9922 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Thu, 3 Dec 2026 11:11:47 +0000 Subject: [PATCH 4/4] Assert only what holds on any machine in the progress widget tests --- tests/fast/api/test_jupyter_progress_bar.py | 36 +++++++++++++-------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/tests/fast/api/test_jupyter_progress_bar.py b/tests/fast/api/test_jupyter_progress_bar.py index 200309a37..27d75edcd 100644 --- a/tests/fast/api/test_jupyter_progress_bar.py +++ b/tests/fast/api/test_jupyter_progress_bar.py @@ -76,7 +76,11 @@ def widgets(self): def progress_widgets(messages): - """The FloatProgress widgets the messages open, in order, each with its opening state and its value updates.""" + """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"] @@ -233,10 +237,11 @@ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ipywidgets.FloatProgress = Recorded -""", - f""" con = duckdb.connect() con.execute("SET progress_bar_time = 0") +""", + f""" +made.clear() con.execute("{QUERY}").fetchall() print(json.dumps(made)) """, @@ -307,8 +312,7 @@ def test_a_query_that_fails_midway_keeps_the_kernel(tmp_path): [error] = failed.errors() assert error["ename"] == "InvalidInputException" assert "stopped midway" in error["evalue"] - [shown] = failed.widgets() - assert shown["values"] + assert len(failed.widgets()) == 1 assert not after.errors() [widget] = after.widgets() assert_ends_at_100(widget) @@ -326,6 +330,8 @@ def test_an_interrupt_while_the_widget_shows_interrupts_the_query(tmp_path): 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() @@ -336,9 +342,8 @@ def test_an_interrupt_while_the_widget_shows_interrupts_the_query(tmp_path): ], ) assert_alive(kernel) - assert kernel.cells[0].stdout() == "RuntimeError Query interrupted\n" - [widget] = kernel.widgets() - assert widget["values"] + assert kernel.cells[1].stdout() == "RuntimeError Query interrupted\n" + assert len(kernel.cells[1].widgets()) == 1 @pytest.mark.timeout(120) @@ -351,16 +356,19 @@ def test_an_interrupt_raised_inside_the_widget_interrupts_the_query(tmp_path): + """ import signal +armed = [] + class Interrupting(ipywidgets.FloatProgress): def __setattr__(self, name, value): - if name == "value" and not getattr(self, "interrupted", False): - object.__setattr__(self, "interrupted", True) + 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") @@ -415,8 +423,8 @@ def test_a_widget_that_raises_fails_the_statement(tmp_path, widget, message): IMPORT_DUCKDB + widget + "ipywidgets.FloatProgress = Broken\n", f""" con = duckdb.connect() -con.execute("SET progress_bar_time = 0") try: + con.execute("SET progress_bar_time = 0") con.execute("{QUERY}").fetchall() except duckdb.Error as error: print(type(error).__name__) @@ -438,9 +446,11 @@ def test_the_kernel_exits_cleanly_after_showing_bars(tmp_path): tmp_path, [ IMPORT_DUCKDB - + f""" + + """ con = duckdb.connect() con.execute("SET progress_bar_time = 0") +""", + f""" for _ in range(3): con.execute("{QUERY}").fetchall() """, @@ -448,5 +458,5 @@ def test_the_kernel_exits_cleanly_after_showing_bars(tmp_path): env={"PYTHONMALLOC": "debug"}, ) assert_alive(kernel) - assert len(kernel.widgets()) == 3 + assert len(kernel.cells[1].widgets()) == 3 assert kernel.returncode == 0, kernel.stderr