From 37dd548b90cc2eec472592e24de460b7dba551e6 Mon Sep 17 00:00:00 2001 From: "j.belina" Date: Tue, 3 Nov 2026 02:48:53 +0100 Subject: [PATCH 1/3] Pass config to pytest_report_teststatus in the nbdime reporter pytest 9 has a built-in pytest_report_teststatus implementation (in _pytest/subtests.py) that takes config. NbdimeReporter calls the hook without it, so pluggy raises HookCallError: hook call must provide argument 'config' and a run with --nbdime ends with an internal error. This is why test_nbdime fails with pytest 9. Co-Authored-By: Claude Opus 5.5 --- nbval/nbdime_reporter.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nbval/nbdime_reporter.py b/nbval/nbdime_reporter.py index 64871a2..e38c574 100644 --- a/nbval/nbdime_reporter.py +++ b/nbval/nbdime_reporter.py @@ -56,7 +56,7 @@ def __init__(self, config, file=None): def pytest_runtest_logreport(self, report): """Store all test reports for evaluation on finish""" rep = report - res = self.config.hook.pytest_report_teststatus(report=rep) + res = self.config.hook.pytest_report_teststatus(report=rep, config=self.config) cat, letter, word = res self.stats.setdefault(cat, []).append(rep) From 71c0ba12b4b4349b3241fde1a2da993664966991 Mon Sep 17 00:00:00 2001 From: "j.belina" Date: Mon, 2 Nov 2026 23:47:05 +0100 Subject: [PATCH 2/3] Add --nbval-kernel-startup-retries to start a new kernel when one fails nbval starts each notebook's kernel once. If that kernel dies or does not reply within the startup timeout, every cell of the notebook errors. With --nbval-kernel-startup-retries=N, nbval shuts the failed kernel down and starts a new one, up to N times, and raises the last error if all of them fail. Each new kernel gets new ports, so a port that another process took in the meantime does not stop it. The default of 0 keeps the current behaviour. Co-Authored-By: Claude Opus 5.5 --- nbval/kernel.py | 47 ++++++++++++++++++++++-------------- nbval/plugin.py | 6 +++++ tests/test_kernel_startup.py | 37 ++++++++++++++++++++++++++++ 3 files changed, 72 insertions(+), 18 deletions(-) create mode 100644 tests/test_kernel_startup.py diff --git a/nbval/kernel.py b/nbval/kernel.py index b567a7f..a12cb20 100644 --- a/nbval/kernel.py +++ b/nbval/kernel.py @@ -45,23 +45,32 @@ def get_kernel_spec(self, kernel_name): return super(NbvalKernelspecManager, self).get_kernel_spec(kernel_name) -def start_new_kernel(startup_timeout=60, kernel_name='python', **kwargs): - """Start a new kernel, and return its Manager and Client""" - logger.debug('Starting new kernel: "%s"' % kernel_name) - km = KernelManager(kernel_name=kernel_name, - kernel_spec_manager=NbvalKernelspecManager()) - km.start_kernel(**kwargs) - kc = km.client() - kc.start_channels() - try: - kc.wait_for_ready(timeout=startup_timeout) - except RuntimeError: - logger.exception('Failure starting kernel "%s"', kernel_name) - kc.stop_channels() - km.shutdown_kernel() - raise - - return km, kc +def start_new_kernel(startup_timeout=60, kernel_name='python', + startup_retries=0, **kwargs): + """Start a new kernel, and return its Manager and Client + + If the kernel dies or does not reply within `startup_timeout` seconds, + a new kernel is started, up to `startup_retries` times. Each new kernel + gets new ports, so it does not fail if another process took one of the + ports chosen for the previous kernel before that kernel could bind it. + """ + for attempt in range(startup_retries + 1): + logger.debug('Starting new kernel: "%s"' % kernel_name) + km = KernelManager(kernel_name=kernel_name, + kernel_spec_manager=NbvalKernelspecManager()) + km.start_kernel(**kwargs) + kc = km.client() + kc.start_channels() + try: + kc.wait_for_ready(timeout=startup_timeout) + except RuntimeError: + logger.exception('Failure starting kernel "%s"', kernel_name) + kc.stop_channels() + km.shutdown_kernel() + if attempt == startup_retries: + raise + else: + return km, kc class RunningKernel(object): @@ -75,7 +84,8 @@ class RunningKernel(object): this class. """ - def __init__(self, kernel_name, cwd=None, startup_timeout=60): + def __init__(self, kernel_name, cwd=None, startup_timeout=60, + startup_retries=0): """ Initialise a new kernel specify that matplotlib is inline and connect the stderr. @@ -84,6 +94,7 @@ def __init__(self, kernel_name, cwd=None, startup_timeout=60): self.km, self.kc = start_new_kernel( startup_timeout=startup_timeout, + startup_retries=startup_retries, kernel_name=kernel_name, stderr=open(os.devnull, 'w'), cwd=cwd, diff --git a/nbval/plugin.py b/nbval/plugin.py index 08bd88d..a76a68b 100644 --- a/nbval/plugin.py +++ b/nbval/plugin.py @@ -101,6 +101,11 @@ def pytest_addoption(parser): type=float, help='Timeout for kernel startup, in seconds.') + group.addoption('--nbval-kernel-startup-retries', action='store', default=0, + type=int, + help='How often to start a new kernel when a kernel dies ' + 'or does not respond during startup.') + group.addoption('--sanitize-with', help='(deprecated) Alias of --nbval-sanitize-with') @@ -265,6 +270,7 @@ def setup(self): kernel_name, cwd=str(self.fspath.dirname), startup_timeout=self.config.option.nbval_kernel_startup_timeout, + startup_retries=self.config.option.nbval_kernel_startup_retries, ) self.setup_sanitize_files() if getattr(self.parent.config.option, 'cov_source', None): diff --git a/tests/test_kernel_startup.py b/tests/test_kernel_startup.py new file mode 100644 index 0000000..02d1d75 --- /dev/null +++ b/tests/test_kernel_startup.py @@ -0,0 +1,37 @@ +import pytest + +from nbval.kernel import start_new_kernel + + +def kernel_managers(mocker, dying): + """Replace KernelManager by mocks whose first `dying` kernels die.""" + managers = [] + + def new_kernel_manager(**kwargs): + km = mocker.Mock() + if len(managers) < dying: + km.client.return_value.wait_for_ready.side_effect = RuntimeError( + 'Kernel died before replying to kernel_info') + managers.append(km) + return km + + mocker.patch('nbval.kernel.KernelManager', side_effect=new_kernel_manager) + return managers + + +def test_a_kernel_that_dies_is_replaced(mocker): + managers = kernel_managers(mocker, dying=1) + + km, kc = start_new_kernel(startup_retries=1) + + assert km is managers[1] + managers[0].shutdown_kernel.assert_called_once() + + +def test_the_error_is_raised_when_all_kernels_die(mocker): + managers = kernel_managers(mocker, dying=2) + + with pytest.raises(RuntimeError, match='Kernel died'): + start_new_kernel(startup_retries=1) + + assert len(managers) == 2 From 7c09b91fb652bb74a4b3738a4737e96939d11862 Mon Sep 17 00:00:00 2001 From: "j.belina" Date: Tue, 3 Nov 2026 02:24:32 +0100 Subject: [PATCH 3/3] Keep the history of IPython kernels in memory Kernels that start at the same time, e.g. the first kernels of a pytest-xdist session in a fresh home directory, all create and open the profile's history.sqlite. IPython takes the locked database for a corrupt one and renames it, and a kernel dies when another kernel has renamed the file first: File "IPython/core/history.py", line 105, in catch_corrupt_db self.hist_file.rename(newpath) FileNotFoundError: [Errno 2] No such file or directory Start IPython kernels with --HistoryManager.hist_file=:memory:, as nbclient does by default. nbval runs cells with store_history=False, so the file never held anything from the tests. Co-Authored-By: Claude Opus 5.5 --- nbval/kernel.py | 7 ++++++- tests/test_kernel_startup.py | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/nbval/kernel.py b/nbval/kernel.py index a12cb20..3b8b6d9 100644 --- a/nbval/kernel.py +++ b/nbval/kernel.py @@ -58,7 +58,12 @@ def start_new_kernel(startup_timeout=60, kernel_name='python', logger.debug('Starting new kernel: "%s"' % kernel_name) km = KernelManager(kernel_name=kernel_name, kernel_spec_manager=NbvalKernelspecManager()) - km.start_kernel(**kwargs) + extra_arguments = [] + if km.ipykernel or kernel_name == CURRENT_ENV_KERNEL_NAME: + # Keep the history in memory, as nbclient does. Kernels that start + # at the same time otherwise race on the profile's history.sqlite. + extra_arguments.append('--HistoryManager.hist_file=:memory:') + km.start_kernel(extra_arguments=extra_arguments, **kwargs) kc = km.client() kc.start_channels() try: diff --git a/tests/test_kernel_startup.py b/tests/test_kernel_startup.py index 02d1d75..2ea2628 100644 --- a/tests/test_kernel_startup.py +++ b/tests/test_kernel_startup.py @@ -1,7 +1,15 @@ +import os + +import nbformat import pytest from nbval.kernel import start_new_kernel +from utils import build_nb + + +pytest_plugins = "pytester" + def kernel_managers(mocker, dying): """Replace KernelManager by mocks whose first `dying` kernels die.""" @@ -35,3 +43,17 @@ def test_the_error_is_raised_when_all_kernels_die(mocker): start_new_kernel(startup_retries=1) assert len(managers) == 2 + + +def test_ipython_kernels_keep_their_history_in_memory(testdir): + nb = build_nb([ + "from IPython import get_ipython\n" + "assert get_ipython().history_manager.hist_file == ':memory:'", + ]) + nbformat.write(nb, os.path.join(str(testdir.tmpdir), 'test_history.ipynb')) + + result = testdir.inline_run('--nbval-lax', '--nbval-current-env') + + passed, skipped, failed = result.listoutcomes() + assert len(passed) == 1 + assert not failed