Skip to content

FIX Callback transport don't store connections forever - #34870

Merged
jeremiedbb merged 21 commits into
scikit-learn:mainfrom
jeremiedbb:fix-callback-transport-fd-2
Nov 23, 2026
Merged

jeremiedbb merged 21 commits into
scikit-learn:mainfrom
jeremiedbb:fix-callback-transport-fd-2

Conversation

@jeremiedbb

@jeremiedbb jeremiedbb commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

Fixes #34734

This PR fixes the second (and main) source of leaking threads and file descriptors. It ensures that we don't keep open connections forever, even when they're not useful anymore.
(I'd rather have #34856 merged first to have easier merge conflicts but the 2 PRs fix 2 independent problems and can be reviewed independently)

Currently, we store every connection in a process-wide dict (_worker_connections) and never remove them. So they stay open until the worker is shut down (which can take a while since loky can reuse workers for subsequent tasks). Making it a lru cache mitigates the issue a bit, but not entirely since it still allows to grow the number of open connections far beyond what's actually needed.

This PR proposes to refactor the transport module a bit to add a new object (Channel) that abstracts both end of the communication channel (listener in the main process and clients in the workers). This way the connection made to send messages is tied to the channel and dies with it. The connection alone can also be closed to immediately free the resources instead of waiting for the callback to be collected (i.e. at teardown for scoring monitor).

Maybe it could have been fixed with a bit less refactoring but I actually find it cleaner and simpler. Now the only public object from transport is Channel (at least when we make transport public :) ). The callbacks create and store a channel and then call methods of the channel.

Comment on lines +128 to +131
# Nothing more will be sent for this fit. The channel itself outlives the fit,
# since this callback keeps logging across fits, but the connection a worker
# copy holds is released here rather than whenever that copy is collected.
self._channel.disconnect()

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That part is new and useful to stop the leak because callbacks are held a reference cycles and thus are not collected immediately. Adding the fact that loky reuses worker makes the callbacks and thus the channels and thus the connections alive for a very long time, which gives time for the number of file descriptors to grow too much.
So ideally the better fix would be to avoid that reference cycle (it comes from the context tree holding references to both its parent and children), which I'm planning to investigate as a follow-up work. In the meantime the disconnect fix is acceptable.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The callback context no longer introduce reference cycles but I think we should keep this to release system resources deterministically as soon as no longer needed rather than rely on GC.

Comment on lines +166 to 176
def test_channel_state_is_not_walked_by_the_pickler(factory, monkeypatch):
"""Check that pickling a callback never traverses state its channels write to.

An estimator carrying a callback can be pickled by a background thread, e.g. loky's
queue feeder dispatching a task to a worker, while the listener thread of that same
queue feeder dispatching a task to a worker, while a channel thread of that same
callback mutates the callback's state as messages come in. Pickling a container that
another thread mutates breaks the dump, which joblib reports as "Could not pickle
the task to send it to the workers".

The check runs from a hook, i.e. while the listeners are up, which is when such a
The check runs from a hook, i.e. while the channels are up, which is when such a
dispatch would happen.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had to rewrite this test because it used to inspect the global _message_consumers dict which is no longer there. Instead I monkeypatch Channel.init to record the message_consumer. The intent of the test is still the same and it still fails if we remove the fix from #34821

Comment on lines +1 to +3
- Fixed a leak of file descriptors and background threads by
:class:`callback.ScoringMonitor` and :class:`callback.ProgressBar`.
By :user:`Jérémie du Boisberranger <jeremiedbb>`. :pr:`34856`,

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this looks weird but the idea is to reference this PR and #34856 in a single changelog entry. Look at the generated changelog, it looks as expected.

@jeremiedbb jeremiedbb added this to Labs Sep 2, 2026
@jeremiedbb jeremiedbb moved this to PR waiting for reviews in Labs Sep 2, 2026
@jeremiedbb

jeremiedbb commented Sep 2, 2026 •

Copy link
Copy Markdown
Member Author

The missing coverage is for a line that was already uncovered before the refactoring (see https://app.codecov.io/gh/scikit-learn/scikit-learn/pull/34870). I'd rather ignore it for this PR and open a follow up PR to write a test to cover this line (unrelated to this PR).

@FrancoisPgm FrancoisPgm left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the refactoring, the Channel class looks much cleaner to me.
I have some nitpicks, some small suggestions, and one potential important issue that might be worth discussing but which is reaching the limit of my understanding of threading.

EDIT : I tried the full fix by including the changes from #34856 to this branch, and testing with the active thread counts on a meta-estimator with callbacks works (and fails on main), so I am now confident enough to approve the PR.

Comment thread sklearn/callback/_transport.py Resolved
Comment thread sklearn/callback/_scoring_monitor.py Resolved
Comment thread sklearn/callback/_scoring_monitor.py Resolved
Comment thread sklearn/callback/_transport.py Resolved


def open_listener(message_consumer, *, owner=None):
def open_listener(message_consumer):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

open_listener and close_listener now only appear inside Channel, they could become private helpers.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They are: they are defined in a private module (_transport.py) and are not exposed in/by any public module.

Comment thread sklearn/callback/_transport.py Resolved
@FrancoisPgm FrancoisPgm moved this from PR waiting for reviews to PR in progress in Labs Oct 19, 2026
@github-actions github-actions Bot added the size/L label Nov 5, 2026
@jeremiedbb jeremiedbb moved this from PR in progress to PR waiting for reviews in Labs Nov 6, 2026

@ogrisel ogrisel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some feedback. The core of this PR looks good and I confirm it can fix the problem when combined with the listener / _accept fix from the other PR.

Comment thread sklearn/callback/_transport.py Resolved
Comment thread sklearn/callback/_transport.py Resolved
@ogrisel ogrisel moved this from PR waiting for reviews to PR in progress in Labs Nov 16, 2026
@ogrisel

ogrisel commented Nov 20, 2026

Copy link
Copy Markdown
Member

I merged #34856 to main and will resolve the conflicts.

Bring in the accept-thread shutdown from scikit-learn#34856. close_listener wakes the
accept thread with an unauthenticated connection, a rejected handshake
keeps the listener open, and the accept and handler threads are named.

Co-authored-by: Olivier Grisel <[email protected]>
disconnect is kept so non-propagated callbacks can free the worker
socket in teardown, before cyclic GC collects the copy. Close the
Client explicitly and test that the handler thread exits while the
copy is still alive. Leftover-thread checks already use the named
transport threads.

Co-authored-by: Olivier Grisel <[email protected]>
cursoragent and others added 6 commits November 21, 2026 14:52
Serialize cross-process `Channel.send` and `Channel.disconnect` with a
per-Channel lock (re-initialized on unpickling), drop broken connections
on error, and close accepted server-side connections in `_handle`'s
`finally` block. Add unit and nested loky+threading regression tests.

Co-authored-by: Olivier Grisel <[email protected]>
@github-actions github-actions Bot added size/XL and removed size/L labels Nov 21, 2026

@ogrisel ogrisel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I merged main, resolved the conflicts, addressed my previous review comments and iteratively improved the PR to increase test coverage, discovered a new bug (deadlocks and crashes) related to nested parallelism. This is now also fixed and the changelog entry has been updated to reflect the wider scope of this fix.

The PR LGTM. +1 for merge on my side.

cc @FrancoisPgm @jeremiedbb.

@jeremiedbb

Copy link
Copy Markdown
Member Author

Looks good. Not sure we really need the disconnect thing now but we can revisit later. Let's merge

@jeremiedbb
jeremiedbb merged commit eff735c into scikit-learn:main Nov 23, 2026
67 of 70 checks passed
@github-project-automation github-project-automation Bot moved this from PR in progress to Done in Labs Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: Callback's _worker_connections cache grows too big

4 participants