Skip to content

Race when pickling RecordingCallback during process-based parallelism on Python 3.14 #34792

Closed
Shreevable/scikit-learn
#2

Description

@mcepl

Warning

This issue is not yet ready for a PR. If you are interested in contributing to scikit-learn, please have a look at our contributing guidelines, and in particular the sections for new contributors and the "Needs triage" label.

Introduce yourself

While packaging upgrade of Python 3.14.7 for openSUSE/Factory, we hit this sudden failure of test_function_no_callback_support[RecordingCallback-processes-2] on i586 architecture (see complete build log with all packages used and steps taken to reproduce, basically just running the test suite).

Describe the bug and give evidence about its user-facing impact

The impact is that the test suite doesn’t pass for us, and we have to skip one more test.

Steps/Code to Reproduce

See above, just running the test suite leads to:


Expected Results

just running the test suite

Actual Results

[ 1518s] =================================== FAILURES ===================================
[ 1518s] _______ test_function_no_callback_support[RecordingCallback-processes-2] _______
[ 1518s] [gw0] linux -- Python 3.14.7 /usr/bin/python3.14
[ 1518s] joblib.externals.loky.process_executor._RemoteTraceback: 
[ 1518s] """
[ 1518s] Traceback (most recent call last):
[ 1518s]   File "/usr/lib/python3.14/site-packages/joblib/externals/loky/backend/queues.py", line 159, in _feed
[ 1518s]     obj_ = dumps(obj, reducers=reducers)
[ 1518s]   File "/usr/lib/python3.14/site-packages/joblib/externals/loky/backend/reduction.py", line 214, in dumps
[ 1518s]     dump(obj, buf, reducers=reducers, protocol=protocol)
[ 1518s]     ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[ 1518s]   File "/usr/lib/python3.14/site-packages/joblib/externals/loky/backend/reduction.py", line 207, in dump
[ 1518s]     _LokyPickler(file, reducers=reducers, protocol=protocol).dump(obj)
[ 1518s]     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^
[ 1518s]   File "/usr/lib/python3.14/site-packages/joblib/externals/cloudpickle/cloudpickle.py", line 1313, in dump
[ 1518s]     return super().dump(obj)
[ 1518s]            ~~~~~~~~~~~~^^^^^
[ 1518s] RuntimeError: list changed size during iteration
[ 1518s] when serializing dict item 'record'
[ 1518s] when serializing sklearn.callback.tests._utils.RecordingCallback state
[ 1518s] when serializing sklearn.callback.tests._utils.RecordingCallback object
[ 1518s] when serializing list item 0
[ 1518s] when serializing dict item '_skl_callbacks'
[ 1518s] when serializing sklearn.callback.tests._utils.MaxIterEstimator state
[ 1518s] when serializing sklearn.callback.tests._utils.MaxIterEstimator object
[ 1518s] when serializing tuple item 0
[ 1518s] when serializing tuple item 1
[ 1518s] when serializing list item 0
[ 1518s] when serializing tuple item 0
[ 1518s] when serializing joblib.parallel.BatchedCalls reconstructor arguments
[ 1518s] when serializing joblib.parallel.BatchedCalls object
[ 1518s] when serializing dict item 'fn'
[ 1518s] when serializing joblib.externals.loky.process_executor._CallItem state
[ 1518s] when serializing joblib.externals.loky.process_executor._CallItem object
[ 1518s] """
[ 1518s] 
[ 1518s] The above exception was the direct cause of the following exception:
[ 1518s] 
[ 1518s] n_jobs = 2, prefer = 'processes'
[ 1518s] Callback = <class 'sklearn.callback.tests._utils.RecordingCallback'>
[ 1518s] 
[ 1518s]     @pytest.mark.parametrize("n_jobs", [1, 2])
[ 1518s]     @pytest.mark.parametrize("prefer", ["threads", "processes"])
[ 1518s]     @pytest.mark.parametrize(
[ 1518s]         "Callback", [RecordingCallback, RecordingAutoPropagatedCallback]
[ 1518s]     )
[ 1518s]     def test_function_no_callback_support(n_jobs, prefer, Callback):
[ 1518s]         """Check callbacks on estimators within function not supporting callbacks.
[ 1518s]     
[ 1518s]         Since the outer function does not support callbacks, there's no shared root context
[ 1518s]         and the context trees of each sub-estimator are independent. As a result, the
[ 1518s]         callback acts as a regular non-propagated callback: its on_fit_begin and on_fit_end
[ 1518s]         are called once for each fit of the sub-estimator and the number of tasks is the sum
[ 1518s]         of the number of tasks from all the sub-estimators.
[ 1518s]         """
[ 1518s]     
[ 1518s]         def clone_and_fit(estimator):
[ 1518s]             clone(estimator).fit()
[ 1518s]     
[ 1518s]         def func(estimator, n_fits, n_jobs, prefer):
[ 1518s]             Parallel(n_jobs=n_jobs, prefer=prefer)(
[ 1518s]                 delayed(clone_and_fit)(estimator) for _ in range(n_fits)
[ 1518s]             )
[ 1518s]     
[ 1518s]         n_fits, max_iter = 5, 7
[ 1518s]         callback = Callback()
[ 1518s]         estimator = MaxIterEstimator(max_iter=max_iter).set_callbacks(callback)
[ 1518s]     
[ 1518s] >       func(estimator, n_fits, n_jobs, prefer)
[ 1518s] 
[ 1518s] /usr/lib/python3.14/site-packages/sklearn/callback/tests/test_callback_support.py:125: 
[ 1518s] _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
[ 1518s] /usr/lib/python3.14/site-packages/sklearn/callback/tests/test_callback_support.py:117: in func
[ 1518s]     Parallel(n_jobs=n_jobs, prefer=prefer)(
[ 1518s] /usr/lib/python3.14/site-packages/sklearn/utils/parallel.py:91: in __call__
[ 1518s]     return super().__call__(iterable_with_config_and_warning_filters)
[ 1518s]            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[ 1518s] /usr/lib/python3.14/site-packages/joblib/parallel.py:2072: in __call__
[ 1518s]     return output if self.return_generator else list(output)
[ 1518s]                                                 ^^^^^^^^^^^^
[ 1518s] /usr/lib/python3.14/site-packages/joblib/parallel.py:1682: in _get_outputs
[ 1518s]     yield from self._retrieve()
[ 1518s] /usr/lib/python3.14/site-packages/joblib/parallel.py:1784: in _retrieve
[ 1518s]     self._raise_error_fast()
[ 1518s] /usr/lib/python3.14/site-packages/joblib/parallel.py:1859: in _raise_error_fast
[ 1518s]     error_job.get_result(self.timeout)
[ 1518s] /usr/lib/python3.14/site-packages/joblib/parallel.py:758: in get_result
[ 1518s]     return self._return_or_raise()
[ 1518s]            ^^^^^^^^^^^^^^^^^^^^^^^
[ 1518s] _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
[ 1518s] 
[ 1518s] self = <joblib.parallel.BatchCompletionCallBack object at 0xce63a828>
[ 1518s] 
[ 1518s]     def _return_or_raise(self):
[ 1518s]         try:
[ 1518s]             if self.status == TASK_ERROR:
[ 1518s] >               raise self._result
[ 1518s] E               _pickle.PicklingError: Could not pickle the task to send it to the workers.
[ 1518s] 
[ 1518s] /usr/lib/python3.14/site-packages/joblib/parallel.py:773: PicklingError
[ 1518s] =========================== short test summary info ============================
[ 1518s] FAILED ../callback/tests/test_callback_support.py::test_function_no_callback_support[RecordingCallback-processes-2] - _pickle.PicklingError: Could not pickle the task to send it to the workers.
[ 1518s] = 1 failed, 33890 passed, 12780 skipped, 247 xfailed, 119 xpassed, 3814 warnings in 1498.23s (0:24:58) =

Versions

- scikit-learn: 1.9.0                                                                                    
 - Python: 3.14.7                                                                                         
 - Architecture: i586                                                                                     
 - joblib: 1.5.3                                                                                          
 - pytest: 9.0.3                                                                                          
 - pytest-xdist: 3.8.0                                                                                    
 - OS: openSUSE Tumbleweed

Interest in fixing the bug

Description

The following scikit-learn test fails intermittently or consistently on i586 with Python 3.14.7:

sklearn/callback/tests/test_callback_support.py::test_function_no_callback_support[RecordingCallback-processes-2]

The failure occurs only for the process-based case with n_jobs=2. The thread-based cases and the n_jobs=1 case pass.

Environment

  • scikit-learn: 1.9.0
  • Python: 3.14.7
  • Architecture: i586
  • joblib: 1.5.3
  • pytest: 9.0.3
  • pytest-xdist: 3.8.0
  • OS: openSUSE Tumbleweed

Reproduction

Run:

pytest -q sklearn/callback/tests/test_callback_support.py \
  -k 'test_function_no_callback_support'

The failing parameter combination is:

test_function_no_callback_support[RecordingCallback-processes-2]

The relevant test code creates a callback-bearing estimator and sends it to process workers through joblib:

callback = RecordingCallback()
estimator = MaxIterEstimator(max_iter=7).set_callbacks(callback)

Parallel(n_jobs=2, prefer="processes")(
    delayed(clone_and_fit)(estimator) for _ in range(5)
)

Actual result

The test fails while joblib/cloudpickle serializes the task:

RuntimeError: list changed size during iteration
when serializing dict item 'record'
when serializing sklearn.callback.tests._utils.RecordingCallback state
when serializing sklearn.callback.tests._utils.RecordingCallback object

This is then reported by joblib as:

_pickle.PicklingError: Could not pickle the task to send it to the workers.

Full traceback excerpt:

Traceback (most recent call last):
  File ".../joblib/externals/loky/backend/queues.py", line 159, in _feed
    obj_ = dumps(obj, reducers=reducers)
  ...
  File ".../joblib/externals/cloudpickle/cloudpickle.py", line 1313, in dump
    return super().dump(obj)
RuntimeError: list changed size during iteration

when serializing dict item 'record'
when serializing sklearn.callback.tests._utils.RecordingCallback state
when serializing sklearn.callback.tests._utils.RecordingCallback object

Expected result

The test should complete successfully, as it does for:

RecordingCallback-threads-1
RecordingCallback-threads-2
RecordingCallback-processes-1
RecordingAutoPropagatedCallback-processes-2

Analysis

RecordingCallback stores its records in a regular list:

self.record = []
self._listener_handle = open_listener(self.record.append, owner=self)

When the worker processes execute the estimator, callback messages are sent back to the parent process. The listener thread appends those messages to callback.record.

At the same time, joblib/cloudpickle serializes the estimator and callback to send work to another process. This means that cloudpickle can be iterating over callback.record while the listener thread appends to it.

The failure appears to be a timing-dependent race between callback message handling and process-task serialization. It was observed on i586, where the slower execution may make the race easier to trigger. I have not determined whether this is caused by a Python 3.14 behavior change, or whether Python 3.14 merely exposes an existing race in the test or callback implementation.

Could this test or callback state be made safe to pickle while callback records are being received? For example, should the live recording state be excluded from the pickled state, synchronized during serialization, or otherwise handled specially?

Activity

  1. added
    Needs Triage
    on Aug 21, 2026
  2. iharshlalakiya commented on Aug 22, 2026

    @iharshlalakiya

    Hi, I'd like to work on this if it's not already claimed.

  3. added and removed
    Needs Triage
    on Aug 24, 2026
  4. lesteve commented on Aug 24, 2026

    @lesteve
    Member

    Thanks @mcepl for the issue, it does seem similar to the one we recently saw in the automated update-lock-file PR CI #34806 and #34804.

    @mcepl could you clarify whether this is a new bug that you observed CPython 3.14.7 and not in CPython 3.14.6?

    cc @FrancoisPgm and @jeremiedbb.

    For reference, I can reproduce on a vanilla CPython (need to install pytest-repeat) with the command below and python 3.14.7. It fails 1-2 times out of 200. It is a lot more likely to happen with free-threaded see #34804 (comment):

    pytest sklearn/callback/tests/test_callback_support.py -k 'test_function_no_callback_support and RecordingCallback-processes-2' --count 200
    
  5. added
    Needs Investigation
    on Aug 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugCallbacksNeeds Investigation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions