test: consolidate GIL subprocess runs (#6212) * test: batch GIL subprocess checks while preserving first-use coverage Run all 17 basic cases in three subprocess batches: the child's main thread, eight sequential workers per case, and eight parallel workers per case. Keep two isolated cross-module initialization cases in each mode to exercise first use with the GIL held and released. Later cases in a batch intentionally share interpreter state. Remove the separate one-worker parametrization, which is covered by the first sequential worker. Each case still creates fresh workers; there is no persistent thread pool. Keep the factory-construction regression and subprocess-harness checks separate. Track the current case in shared memory so failures identify it without printing progress on successful runs. Allow another execution interval when a batch advances to a new case, retaining at least ten seconds for each case rather than imposing a ten-second budget on the whole batch. A deadlock can take one additional interval to detect. This reduces child processes from 71 to 12. A serial CPython 3.14.4 run of test_gil_scoped.py took 3.97 seconds, down from 18.74 seconds before consolidation, including the new worker-exception regression tests. * test: use a pipe for GIL subprocess progress The shared ctypes progress counter can raise FileExistsError before starting a child process on Windows PyPy (pypy/pypy#3488). Replace it with a one-way pipe carrying the current case index. Keep the progress callback in the parent, drain pending messages for failure diagnostics, and retain the last index after EOF. Close both endpoints after subprocess cleanup. This preserves the batched cases and their progress-aware execution allowance. Add a regression that makes multiprocessing.Value raise the same error and verifies that a subprocess batch still succeeds. The regression fails against the previous helper.
diff --git a/tests/test_gil_scoped.py b/tests/test_gil_scoped.py index 2072e26..599f377 100644 --- a/tests/test_gil_scoped.py +++ b/tests/test_gil_scoped.py
@@ -151,6 +151,16 @@ ) +# Keep first-use initialization of the helper module's private internals isolated, +# both with and without the GIL held. Batched cases intentionally share an interpreter; +# their first call into the helper is test_cross_module_gil_released. +PROCESS_TEST_CASES = ( + pytest.param((test_cross_module_gil_released,), id="first_use_gil_released"), + pytest.param((test_cross_module_gil_acquired,), id="first_use_gil_acquired"), + pytest.param(ALL_BASIC_TESTS, id="all_basic_tests"), +) + + def test_all_basic_tests_completeness(): num_found = 0 for key, value in VARS_BEFORE_ALL_BASIC_TESTS.items(): @@ -163,9 +173,8 @@ # Defined after ALL_BASIC_TESTS on purpose: this test is a regression for the # `gil_scoped_release` + factory `py::init` path, not a deadlock check, so it should not -# run in the _run_in_process parametrizations above (whose subprocesses impose a 10s -# timeout; on Windows this test is much slower there due to sleep timer granularity and -# GIL handoff costs). +# run in the subprocess batches (whose cases get at least a 10s execution allowance; +# on Windows this test is much slower due to sleep timer granularity and GIL handoff costs). @pytest.mark.skipif(sys.platform.startswith("emscripten"), reason="Requires threads") def test_init_factory_gil_released_concurrent_construction(): """Concurrent construction via a factory `py::init` with `call_guard<gil_scoped_release>`. @@ -203,7 +212,7 @@ status_writer.send("finished") -def _run_in_process(target, *args, timeout=10, **kwargs): +def _run_in_process(target, *args, timeout=10, get_progress=None, **kwargs): if env.ANDROID or env.IOS or sys.platform.startswith("emscripten"): pytest.skip("Requires subprocess support") @@ -232,11 +241,23 @@ child_started = ( status_reader.poll(timeout=10) and status_reader.recv() == "started" ) - child_finished = ( - child_started - and status_reader.poll(timeout=timeout) - and status_reader.recv() == "finished" - ) + child_finished = False + if child_started: + while True: + previous_progress = None if get_progress is None else get_progress() + child_finished = ( + status_reader.poll(timeout=timeout) + and status_reader.recv() == "finished" + ) + if ( + child_finished + or process.exitcode is not None + or get_progress is None + or get_progress() == previous_progress + ): + break + # Give a newly started case a full execution allowance. + # A deadlock may take one extra wait interval to detect. # A returned test must not look deadlocked while the process shuts down. process.join(timeout=10 if child_finished else 0) if timeout >= 100: @@ -305,6 +326,56 @@ raise exceptions.get() +def _run_test_cases(test_fns, progress_writer, num_threads, parallel): + for index, test_fn in enumerate(test_fns): + progress_writer.send(index) + if num_threads is None: + test_fn() + else: + # Fresh threads per case preserve thread-state creation and cleanup. + _run_in_threads(test_fn, num_threads=num_threads, parallel=parallel) + + +def _run_test_cases_in_process(test_fns, *, num_threads=None, parallel=False): + if env.ANDROID or env.IOS or sys.platform.startswith("emscripten"): + pytest.skip("Requires subprocess support") + + # Shared ctypes can fail on Windows PyPy: https://github.com/pypy/pypy/issues/3488. + progress_reader, progress_writer = multiprocessing.Pipe(duplex=False) + with progress_reader, progress_writer: + current_test = -1 + + def get_progress(): + nonlocal current_test + try: + while progress_reader.poll(): + current_test = progress_reader.recv() + except EOFError: + pass + return current_test + + def current_test_name(): + index = get_progress() + return test_fns[index].__name__ if index >= 0 else "before the first case" + + try: + exitcode = _run_in_process( + _run_test_cases, + test_fns, + progress_writer, + num_threads, + parallel, + get_progress=get_progress, + ) + except RuntimeError as error: + raise RuntimeError( + f"{error} (while running {current_test_name()})" + ) from error + assert exitcode == 0, ( + f"Subprocess exited with {exitcode} while running {current_test_name()}" + ) + + @pytest.mark.skipif(sys.platform.startswith("emscripten"), reason="Requires threads") @pytest.mark.parametrize("parallel", [False, True], ids=["sequential", "parallel"]) def test_run_in_threads_propagates_exception(parallel): @@ -315,61 +386,57 @@ _run_in_threads(fail, num_threads=2, parallel=parallel) -@pytest.mark.skipif(sys.platform.startswith("emscripten"), reason="Requires threads") -@pytest.mark.parametrize("test_fn", ALL_BASIC_TESTS) -@pytest.mark.skipif( - "env.GRAALPY", - reason="GraalPy transiently complains about unfinished threads at process exit", -) -def test_run_in_process_one_thread(test_fn): - """Makes sure there is no GIL deadlock when running in a thread. - - It runs in a separate process to be able to stop and assert if it deadlocks. - """ - assert _run_in_process(_run_in_threads, test_fn, num_threads=1, parallel=False) == 0 - - @skipif_free_threaded @pytest.mark.skipif(sys.platform.startswith("emscripten"), reason="Requires threads") -@pytest.mark.parametrize("test_fn", ALL_BASIC_TESTS) +@pytest.mark.parametrize("test_fns", PROCESS_TEST_CASES) @pytest.mark.skipif( "env.GRAALPY", reason="GraalPy transiently complains about unfinished threads at process exit", ) -def test_run_in_process_multiple_threads_parallel(test_fn): +def test_run_in_process_multiple_threads_parallel(test_fns): """Makes sure there is no GIL deadlock when running in a thread multiple times in parallel. It runs in a separate process to be able to stop and assert if it deadlocks. """ - assert _run_in_process(_run_in_threads, test_fn, num_threads=8, parallel=True) == 0 + _run_test_cases_in_process(test_fns, num_threads=8, parallel=True) @pytest.mark.skipif(sys.platform.startswith("emscripten"), reason="Requires threads") -@pytest.mark.parametrize("test_fn", ALL_BASIC_TESTS) +@pytest.mark.parametrize("test_fns", PROCESS_TEST_CASES) @pytest.mark.skipif( "env.GRAALPY", reason="GraalPy transiently complains about unfinished threads at process exit", ) -def test_run_in_process_multiple_threads_sequential(test_fn): +def test_run_in_process_multiple_threads_sequential(test_fns): """Makes sure there is no GIL deadlock when running in a thread multiple times sequentially. It runs in a separate process to be able to stop and assert if it deadlocks. """ - assert _run_in_process(_run_in_threads, test_fn, num_threads=8, parallel=False) == 0 + # Its first worker also covers the former one-thread parametrization. + _run_test_cases_in_process(test_fns, num_threads=8, parallel=False) @pytest.mark.skipif(sys.platform.startswith("emscripten"), reason="Requires threads") -@pytest.mark.parametrize("test_fn", ALL_BASIC_TESTS) +@pytest.mark.parametrize("test_fns", PROCESS_TEST_CASES) @pytest.mark.skipif( "env.GRAALPY", reason="GraalPy transiently complains about unfinished threads at process exit", ) -def test_run_in_process_direct(test_fn): - """Makes sure there is no GIL deadlock when using processes. +def test_run_in_process_direct(test_fns): + """Exercise the main thread of a fresh interpreter, including its initial GIL state.""" + _run_test_cases_in_process(test_fns) - This test is for completion, but it was never an issue. - """ - assert _run_in_process(test_fn) == 0 + +@pytest.mark.skipif( + env.GRAALPY, + reason="GraalPy transiently complains about unfinished threads at process exit", +) +def test_run_in_process_batch_without_sharedctypes(monkeypatch): + def unavailable_value(*_args, **_kwargs): + raise FileExistsError("Cannot find name for new mmap") + + monkeypatch.setattr(multiprocessing, "Value", unavailable_value) + _run_test_cases_in_process((test_callback_py_obj,)) @pytest.mark.skipif(