Skip to content

Canceling long running tasks #1183

Closed
Closed

Description

@ogrisel

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

  1. ogrisel commented on May 26, 2016

    @ogrisel
    ContributorAuthor

    Terminating the ThreadPool is not enough:

    >>> from time import sleep
    >>> from threading import current_thread
    >>> from multiprocessing.pool import ThreadPool
    >>> def do_stuff():
        while True:
            import threading
            print('%d still alive!' % current_thread().ident)
            sleep(1)
    ...         
    >>> p = ThreadPool(4)
    >>> p.apply_async(do_stuff)
    <multiprocessing.pool.ApplyResult object at 0x7f45cc0c9ba8>
    >>> 139937682646784 still alive!
    139937682646784 still alive!
    
    p.terminate()
    139937682646784 still alive!
    139937682646784 still alive!
    139937682646784 still alive!
    139937682646784 still alive!
  2. jcrist commented on May 27, 2016

    @jcrist
    Member

    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.

  3. ogrisel commented on May 27, 2016

    @ogrisel
    ContributorAuthor

    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.

  4. jcrist commented on May 27, 2016

    @jcrist
    Member

    Sure, closing for now. This might be easier done with the distributed scheduler, as the offending workers can just be killed and restarted.

  5. ogrisel commented on May 28, 2016

    @ogrisel
    ContributorAuthor

    +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.

  6. suryatapavi commented on Feb 15, 2018

    @suryatapavi

    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?

  7. mrocklin commented on Feb 15, 2018

    @mrocklin
    Member

    Python does not allow you to remove threads forcefully. You should write your functions so that they terminate gracefully.

  8. sheridp commented on Mar 15, 2018

    @sheridp

    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.

  9. mrocklin commented on Mar 15, 2018

    @mrocklin
    Member
  10. sheridp commented on Mar 15, 2018

    @sheridp

    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.

  11. mrocklin commented on Mar 15, 2018

    @mrocklin
    Member
  12. louisabraham commented on Oct 11, 2018

    @louisabraham

    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).

  13. mrocklin commented on Oct 11, 2018

    @mrocklin
    Member

    You can cancel any task that has not started yet with the cancel method. Stopping a Python thread once started is not really feasible.

  14. louisabraham commented on Oct 11, 2018

    @louisabraham

    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.cancel could do the job.

    While googling, I saw that pebble implements this feature.

  15. mrocklin commented on Oct 11, 2018

    @mrocklin
    Member
  16. louisabraham commented on Oct 11, 2018

    @louisabraham

    No, we do not plan to kill workers with the cancel command.

    Can I ask why? I only see advantages. Basically, you just increase the rate of success of the Future.cancel function.

    This is something that you should be able to do on your own though.

    Since I don't intend to maintain a fork Dask, can you suggest me how to do it with the current API?

  17. mrocklin commented on Oct 11, 2018

    @mrocklin
    Member
  18. louisabraham commented on Oct 11, 2018

    @louisabraham

    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_SetAsyncExc will 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.cancel method.

  19. mrocklin commented on Oct 11, 2018

    @mrocklin
    Member
  20. louisabraham commented on Oct 11, 2018

    @louisabraham

    No, there is a bunch of other valuable state, like user data.

    Then I agree that killing a worker should not be the default behavior.

    There are two separate things to consider:

    1. the clean PyThreadState_SetAsyncExc: what do you think about it?
    2. a non clean implementation of Future.cancel that kills a worker using retire_workers. It would only be used by aware users that really need it (Las Vegas algorithms or program generation), by providing a special option to Future.cancel. If I implement it, would you consider adding it to dask.distributed?

    Maybe we want to move this discussion to dask.distributed.

  21. mrocklin commented on Oct 12, 2018

    @mrocklin
    Member
  22. louisabraham commented on Oct 12, 2018

    @louisabraham

    We're currently a pure Python project.

    It is accessible through ctypes, so pure Python.

    I'll implement the worker kill for the moment because it is the one I need.

  23. zhanghang1989 commented on Jul 22, 2019

    @zhanghang1989

    @louisabraham any progress on killing python process/worker?

  24. louisabraham commented on Aug 29, 2019

    @louisabraham

    @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:

    This is often used to signal stopping criteria or current parameters between clients.

    Your algorithm could look like that:

    stop = Variable('stopping-criterion')
    while stop.get() is False:
        # do computation

    If you call other functions (from sklearn like in tpot), I would recommend putting them in another process which you can kill when the stop variable is set. Do not forget to use the right parameters to allocate enough cores through your queue system.

  25. MichaelSchreier commented on Jun 5, 2020

    @MichaelSchreier

    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 Cluster and 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 Scheduler which periodically checks for how long each task has been in the processing state 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.

    import dask
    import datetime
    import time
    
    dask.config.set({"distributed.logging.distributed": "ERROR"})
    
    from dask.distributed import SpecCluster, Scheduler, Nanny, Client, Variable, get_client
    from tornado.ioloop import PeriodicCallback
    
    
    DEFAULT_TIMEOUT = 12
    MAX_TIMEOUTS = 1
    DEFAULT_RETURN_VALUE = -1
    
    
    class TimeoutScheduler(Scheduler):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
    
            self.periodic_callbacks["update_timeout_log"] = PeriodicCallback(
                self._check_timeout, 1000
            )
            self.timeout_log = dict()
    
        async def _check_timeout(self):
            """
            Checks all tasks currently being processed and verifies that they are not taking 
            longer than DEFAULT_TIMEOUT seconds. If so all data currently residing on the 
            corresponding worker is fetched and the worker restarted. If a task fails more than
            MAX_TIMEOUTS times a 'Variable' is set which causes the task to immediately return
            DEFAULT_RETURN_VALUE on starting up the next time it is attempted to being executed.
            """
            for worker_address, worker_state in self.workers.items():
                for task_state, cost in worker_state.processing.items():
                    if task_state.key in self.timeout_log:
                        if self.timeout_log[task_state.key]["start_time"] is None:
                            self.timeout_log[task_state.key][
                                "start_time"
                            ] = datetime.datetime.now()
    
                        # kill worker
                        if (
                            datetime.datetime.now()
                            - self.timeout_log[task_state.key]["start_time"]
                        ).total_seconds() > DEFAULT_TIMEOUT:
                            self.timeout_log[task_state.key]["start_time"] = None
                            self.timeout_log[task_state.key]["n_timeouts"] += 1
    
                            # set cancel Variable in case n_timeouts exceeds MAX_TIMEOUTS
                            if self.timeout_log[task_state.key]["n_timeouts"] > MAX_TIMEOUTS:
                                print(f"cancelling task {task_state.key}")
                                cancel_keys = self.extensions["variables"].variables[
                                    "cancel_keys"
                                ]["value"]
                                cancel_keys[task_state.key] = "cancel"
                                self.extensions["variables"].variables["cancel_keys"][
                                    "value"
                                ] = cancel_keys
    
                            # get connection to Worker's Nanny
                            comm = await self.rpc.connect(worker_state.nanny)
    
                            # fetch data from worker before killing it
                            await self.replicate(
                                keys=[task.key for task in worker_state.has_what], n=2
                            )
    
                            # kill worker
                            print(f"killing worker {worker_address}")
                            await comm.write(
                                {"op": "restart"}
                            )  # causes all data stored on that worker to vanish
    
                    else:
                        self.timeout_log[task_state.key] = dict()
                        self.timeout_log[task_state.key]["start_time"] = datetime.datetime.now()
                        self.timeout_log[task_state.key]["n_timeouts"] = 0
    
    
    def sleep(seconds: int):
        from distributed.worker import thread_state
    
        key = thread_state.key
        print(f"I'm task '{key}' and I'm supposed to sleep for {seconds} seconds")
    
        cancel_keys = Variable("cancel_keys", client=get_client()).get()
        if key in cancel_keys and cancel_keys[key] == "cancel":
            print(f"I'm task '{key}' and I'm skipping sleeping")
            return DEFAULT_RETURN_VALUE
    
        time.sleep(seconds)
        seconds += 5
        return seconds
    
    
    def print_results(arg):
        print(arg)
        return arg
    
    
    def run():
        scheduler = {"cls": TimeoutScheduler, "options": {"dashboard_address": ":8787"}}
        workers = {
            "nanny1": {"cls": Nanny, "options": {"nthreads": 1}},
            "nanny2": {"cls": Nanny, "options": {"nthreads": 1}},
        }
        cluster = SpecCluster(scheduler=scheduler, workers=workers)
    
        client = Client(cluster)
    
        cancel_keys = Variable("cancel_keys")
        cancel_keys.set(dict())
    
        graph = {
            "sleep 10": (sleep, 10),
            "sleep 15": (sleep, "sleep 10"),
            "end": (print_results, ["sleep 15"]),
        }
    
        client.get(graph, "end")
    
        time.sleep(2)
        client.close()
        cluster.close()
    
    
    if __name__ == "__main__":
        run()

    Output:

    I'm task 'sleep 10' and I'm supposed to sleep for 10 seconds
    I'm task 'sleep 15' and I'm supposed to sleep for 15 seconds
    killing worker tcp://192.168.0.10:60515
    I'm task 'sleep 15' and I'm supposed to sleep for 15 seconds
    cancelling task sleep 15
    killing worker tcp://192.168.0.10:60518
    I'm task 'sleep 15' and I'm supposed to sleep for 15 seconds
    I'm task 'sleep 15' and I'm skipping sleeping
    [-1]
    
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions