From 43d2bab881a25f1f2faf92e51166ef320fabfdd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A5=E6=BE=84=E4=BA=AE?= Date: Fri, 27 Nov 2026 21:30:06 +0800 Subject: [PATCH] Store displays under the running cell's execution count run_cell increments execution_count before the cell runs, so while a cell runs (and in its post_execute hooks) the cell's own count is execution_count - 1, as IPython's own DisplayPublisher uses. The ZMQ publisher used execution_count outside post_execute, so with store_display_history=True a display was recorded under the next cell and %notebook exported it there. The unit test mocked execution_count=1 while expecting cell 1, which pinned the wrong count; it now mocks the count during cell 1 (2) and covers the post_execute case. A kernel test checks the stored execution count end to end. Fixes #1602 --- ipykernel/zmqshell.py | 6 +++--- tests/test_kernel.py | 13 ++++++++++++ tests/test_zmq_shell.py | 44 +++++++++++++++++++++-------------------- 3 files changed, 39 insertions(+), 24 deletions(-) diff --git a/ipykernel/zmqshell.py b/ipykernel/zmqshell.py index 460d301d0..9085e7c8e 100644 --- a/ipykernel/zmqshell.py +++ b/ipykernel/zmqshell.py @@ -153,9 +153,9 @@ def publish( # type:ignore[override] and HistoryOutput is not None ): # Reference: github.com/ipython/ipython/pull/14998 - exec_count = self.shell.execution_count - if getattr(self.shell.display_pub, "_in_post_execute", False): - exec_count -= 1 + # run_cell increments execution_count before running the cell, so while a cell runs + # (and in its post_execute hooks, e.g. matplotlib's flush) the cell's own count is one less. + exec_count = self.shell.execution_count - 1 outputs = getattr(self.shell.history_manager, "outputs", None) if outputs is not None: outputs.setdefault(exec_count, []).append( diff --git a/tests/test_kernel.py b/tests/test_kernel.py index 270165b1a..8af8d038e 100644 --- a/tests/test_kernel.py +++ b/tests/test_kernel.py @@ -957,3 +957,16 @@ def test_context_vars(): ) stdout, _ = assemble_output(kc.get_iopub_msg, parent_msg_id=msg_id) assert stdout.strip() == "set" + + +def test_display_history_uses_the_cell_execution_count(): + """A display published by a cell is stored under that cell's execution count (for %notebook).""" + with new_kernel(["--ZMQDisplayPublisher.store_display_history=True"]) as kc: + msg_id, content = execute(kc=kc, code="display('shown by this cell')") + wait_for_idle(kc, msg_id) + stored = f"[o.bundle['text/plain'] for o in get_ipython().history_manager.outputs.get({content['execution_count']}, [])]" + _msg_id, reply = execute(kc=kc, code="", user_expressions={"stored": stored}) + assert ( + reply["user_expressions"]["stored"]["data"]["text/plain"] + == "[\"'shown by this cell'\"]" + ) diff --git a/tests/test_zmq_shell.py b/tests/test_zmq_shell.py index c4859cfa0..cfee64821 100644 --- a/tests/test_zmq_shell.py +++ b/tests/test_zmq_shell.py @@ -221,27 +221,29 @@ def test_display_stored_in_history(self): for %notebook magic support, and not stored when disabled. """ for enable in [False, True]: - # Mock shell with history manager - mock_shell = MagicMock() - mock_shell.execution_count = 1 - mock_shell.history_manager.outputs = dict() - mock_shell.display_pub._in_post_execute = False - - self.disp_pub.shell = mock_shell - self.disp_pub.store_display_history = enable - - data = {"text/plain": "test output"} - self.disp_pub.publish(data) - - if enable: - # Check that output was stored in history - stored_outputs = mock_shell.history_manager.outputs[1] - assert len(stored_outputs) == 1 - assert stored_outputs[0].output_type == "display_data" - assert stored_outputs[0].bundle == data - else: - # Should not store anything in history - assert mock_shell.history_manager.outputs == {} + for in_post_execute in [False, True]: + # Mock shell with history manager, while cell 1 runs: run_cell has already + # incremented execution_count to 2. + mock_shell = MagicMock() + mock_shell.execution_count = 2 + mock_shell.history_manager.outputs = dict() + mock_shell.display_pub._in_post_execute = in_post_execute + + self.disp_pub.shell = mock_shell + self.disp_pub.store_display_history = enable + + data = {"text/plain": "test output"} + self.disp_pub.publish(data) + + if enable: + # Check that output was stored in history, under cell 1 + stored_outputs = mock_shell.history_manager.outputs[1] + assert len(stored_outputs) == 1 + assert stored_outputs[0].output_type == "display_data" + assert stored_outputs[0].bundle == data + else: + # Should not store anything in history + assert mock_shell.history_manager.outputs == {} def test_magics(tmp_path):