Repository navigation
Description
Let's assume you decide to write the following in an interactive shell session (or jupyter notebook):
>>> from threading import current_thread
>>> from time import sleep
>>> from dask import delayed, compute
>>> def print_sleep_repeat():
... while True:
... print('I am %s and I am still alive' % current_thread().ident)
... sleep(1)
...
>>> stuff = [delayed(print_sleep_repeat)() for i in range(4)]
>>> compute(*stuff)
I am 140279596939008 and I am still alive
I am 140279613724416 and I am still alive
I am 140279415871232 and I am still alive
I am 140279605331712 and I am still alive
[...]You soon realise that this was a bad idea to submit those annoying tasks your shell. You try to ctrl-c the call to dask.compute but then you realize that it does not prevent the threads to keep on running in the background:
^CTraceback (most recent call last):
File "<ipython-input-2-c5db33259be8>", line 10, in <module>
compute(*stuff)
File "/home/ogrisel/code/dask/dask/base.py", line 110, in compute
results = get(dsk, keys, **kwargs)
File "/home/ogrisel/code/dask/dask/threaded.py", line 57, in get
**kwargs)
File "/home/ogrisel/code/dask/dask/async.py", line 474, in get_async
key, res, tb, worker_id = queue.get()
File "/usr/lib/python3.5/queue.py", line 164, in get
self.not_empty.wait()
File "/usr/lib/python3.5/threading.py", line 293, in wait
waiter.acquire()
KeyboardInterrupt
>>> I am 140279613724416 and I am still alive
I am 140279596939008 and I am still alive
I am 140279415871232 and I am still alive
I am 140279605331712 and I am still alive
I am 140279613724416 and I am still alive
I am 140279605331712 and I am still alive
I am 140279596939008 and I am still alive
I am 140279415871232 and I am still alive
I think interrupting the call to dask.compute should try its best to interrupt the all the scheduled tasks. Possible solutions:
1- Terminate the whole ThreadPool (although I am not even sure that can save this issue)
2- Leverage the ctypes.pythonapi.PyThreadState_SetAsyncExc trick http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python
3- Try to use signal.pthread_kill which should make it possible to also kill long running compiled extensions that never reach back into the Python interpreter to receive the PyThreadState_SetAsyncExc interruption.
The ctypes.pythonapi.PyThreadState_SetAsyncExc trick is nice because it should not run the risk of deadlocking the python process by messing with the GIL or other Python run-time state.
Activity
ogrisel commentedon May 26, 2016
Terminating the
ThreadPoolis not enough:jcrist commentedon May 27, 2016
Just spent a bit of time playing around with this. This is not a simple problem to solve (for threads at least). I have it working using the ctypes hack, but the exceptions thrown in the threads go uncaught, which tears down the interpreter. To properly catch them we'd need to implement our own subclass of
Pool. This is doable, but seems a bit hacky (especially the ctypes bit), so I'm unsure if it's worth it.ogrisel commentedon May 27, 2016
Thanks for investigating. I was not aware of the need to subclass Pool. Indeed this sounds a bit too complex. Maybe we can close this issue as a nice to have for later.
If someone comes up with a strong need for this feature maybe add a comment to issue to motivate your use case and make this a higher priority request.
jcrist commentedon May 27, 2016
Sure, closing for now. This might be easier done with the distributed scheduler, as the offending workers can just be killed and restarted.
ogrisel commentedon May 28, 2016
+1 for doing it in distributed first. I think this is most useful on a cluster potentially shared by several executors. For dask on a local setup, it's easy to kill the local python process and restarting.
suryatapavi commentedon Feb 15, 2018
how to remove threads? My code iterative spawns threads in batches. But, the threads from the previous iteration does not die. I tried cancelling the futures as completed and closing/restarting client. Every unused thread is holding MBs of memory and if not cleared, will eventually crash. Any idea what to do?
mrocklin commentedon Feb 15, 2018
Python does not allow you to remove threads forcefully. You should write your functions so that they terminate gracefully.
sheridp commentedon Mar 15, 2018
I think the ability to kill (or better yet send a SIGINT / KeyboardInterrupt) would be very useful. My use case: I am using distributed with docker-py to kick off containers that are running very long simulations (and later analyzing the data with dask). Sometimes I start a simulation and realize later that some parameters weren't right and I need to kill it. One solution I've come up with is to have my dask worker start the container in detached mode, use get_client to get a local client, and then poll the scheduler using get_metadata. If I want to cancel a run, I can set_metadata on the scheduler. I think this would work, but it feels a little hacky. I think sending a SIGINT to the worker when calling Future.cancel (or something similar) would be cleaner.
mrocklin commentedon Mar 15, 2018
sheridp commentedon Mar 15, 2018
Unfortunately, it's not something that can be done in python easily (that I'm aware of). Signals are only sent to the main thread. The best workaround I've seen is to send it to the main thread and have the main thread notify the worker threads by another means (queues or something) -- which would kind of defeat the whole purpose. For dask.distributed, the best I can think of would be to have future.cancel notify the Nanny which would then send the SIGINT to the worker. If you only have 1 thread/worker process, it would work. Not sure how to deal with multiple workers.
mrocklin commentedon Mar 15, 2018
louisabraham commentedon Oct 11, 2018
Hi, what is the status of this?
Stopping long running jobs would be a really useful feature, in particular for Las Vegas algorithms that require restarts, or when evaluating generated programs (see tpot).
mrocklin commentedon Oct 11, 2018
You can cancel any task that has not started yet with the cancel method. Stopping a Python thread once started is not really feasible.
louisabraham commentedon Oct 11, 2018
I agree it is not possible with a thread, but it is possible with a process, with Process.terminate.
As for the interface, I think
Future.cancelcould do the job.While googling, I saw that pebble implements this feature.
mrocklin commentedon Oct 11, 2018
louisabraham commentedon Oct 11, 2018
Can I ask why? I only see advantages. Basically, you just increase the rate of success of the
Future.cancelfunction.Since I don't intend to maintain a fork Dask, can you suggest me how to do it with the current API?
mrocklin commentedon Oct 11, 2018
louisabraham commentedon Oct 11, 2018
Oh, I understand now: a single worker has a ThreadPoolExecutor that executes many tasks.
I see how I could use
retire_workers, but now that I understand your point, I don't want to kill a worker :)Would you consider adding this feature in the case there is only one thread per worker?
Also, I think it is possible to try raising an exception with PyThreadState_SetAsyncExc.
With those proposals,
PyThreadState_SetAsyncExcwill be able to stop pure Python code.If a user wants to cancel tasks that execute code outside of the interpreter, he has to set only one thread per worker, and maybe specify an optional argument defaulting to False in the
Future.cancelmethod.mrocklin commentedon Oct 11, 2018
louisabraham commentedon Oct 11, 2018
Then I agree that killing a worker should not be the default behavior.
There are two separate things to consider:
PyThreadState_SetAsyncExc: what do you think about it?Future.cancelthat kills a worker usingretire_workers. It would only be used by aware users that really need it (Las Vegas algorithms or program generation), by providing a special option toFuture.cancel. If I implement it, would you consider adding it todask.distributed?Maybe we want to move this discussion to
dask.distributed.mrocklin commentedon Oct 12, 2018
louisabraham commentedon Oct 12, 2018
It is accessible through ctypes, so pure Python.
I'll implement the worker kill for the moment because it is the one I need.
zhanghang1989 commentedon Jul 22, 2019
@louisabraham any progress on killing python process/worker?
louisabraham commentedon Aug 29, 2019
@zhanghang1989 No, I implemented it without dask.
I don't think the Coordination Primitives existed when I wrote my code.
In particular, Global Variables seem to be able to answer to some use cases:
Your algorithm could look like that:
If you call other functions (from sklearn like in tpot), I would recommend putting them in another process which you can kill when the
stopvariable is set. Do not forget to use the right parameters to allocate enough cores through your queue system.MichaelSchreier commentedon Jun 5, 2020
I'm in a similar situation where tasks may randomly get stuck (either in C-code that I don't own or during communication with a database) and the only clean option right now is to completely terminate the entire
Clusterand rerun everything. Obviously this is far from ideal.I just hacked together this minimal example that seems to do the job for the "single-thread-per-worker" case. I can already see multiple gotchas and expect to encounter many more should I go forward and implement something like this in a real system. Use at your own risk, you've been warned.
The solution works by creating a custom
Schedulerwhich periodically checks for how long each task has been in theprocessingstate and restarts the associated worker should the lifetime of the task exceed a predefined threshold.In my real-world use case I don't need the return values of the tasks (they save their results to disk) and can deal with failed tasks in the pipeline. Hence I modify the task to return a default value if it has timed out too often.
Output: