Dask needs the main thread: import dask_jobqueue there and avoid a process-based LocalCluster in a worker thread
Symptom#
Running an analysis that uses Dask from a worker thread of a server fails in two ways. A process-based LocalCluster fails with:
InstantiationException Error in call to target 'distributed.deploy.local.LocalCluster':
RuntimeError('Nanny failed to start.')
Importing dask_jobqueue in a worker thread fails because the import calls signal.signal.
Cause#
The Nanny of a process-based LocalCluster needs signal handlers, and only the main thread can set them. dask_jobqueue calls signal.signal when it is imported.
Fix#
Import dask_jobqueue once at server start, from the main thread, and restore the old SIGINT handler after the import. After that, any thread can use the library. Run with no cluster, or use a threads-only cluster, LocalCluster(processes=False), which has no Nanny. Do not start a subprocess just to get the main thread.
Evidence#
A dfanalyzer run in the server process with cluster=none finished in 5.53 s on 8,060 files. A run on the dashboard's own LocalCluster(processes=False) also worked, with no child process (pgrep found none).
Also found by searching
- RuntimeError('Nanny failed to start.')
- ValueError: signal only works in main thread of the main interpreter
- run dask or dfanalyzer inside a worker thread
- dask_jobqueue import fails in a thread