Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TaskCancellation #7669

Merged
merged 50 commits into from
Apr 25, 2020
Merged
Show file tree
Hide file tree
Changes from 35 commits
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
169c540
Smol comment
ijrsvt Mar 19, 2020
682c5b5
Merge branch 'master' into TaskCancellation
ijrsvt Mar 25, 2020
2d020ba
WIP, not passing ray.init
ijrsvt Mar 25, 2020
1958e05
Fixed small problem
ijrsvt Mar 25, 2020
4fdeb5a
wip
ijrsvt Mar 31, 2020
40b2bb5
Pseudo interrupt things
ijrsvt Mar 31, 2020
d1295c3
Basic prototype operational
ijrsvt Mar 31, 2020
269a3b1
Merge branch 'master' of github.com:ijrsvt/ray into TaskCancellation
ijrsvt Apr 1, 2020
028d9f7
correct proc title
ijrsvt Apr 2, 2020
a4b58e5
Mostly done
ijrsvt Apr 7, 2020
33ad6a1
Cleanup
ijrsvt Apr 7, 2020
4f7eec7
cleaner raylet error
ijrsvt Apr 7, 2020
cc3ca28
Cleaning up a few loose ends
ijrsvt Apr 7, 2020
bd47066
Fixing Race Conds
ijrsvt Apr 7, 2020
c0b5ab4
Prelim testing
ijrsvt Apr 7, 2020
58c8bed
Fixing comments and adding second_check for kill
ijrsvt Apr 8, 2020
bae435f
Working_new_impl
ijrsvt Apr 9, 2020
9ab039d
demo_ready
ijrsvt Apr 9, 2020
d85496d
Fixing my english
ijrsvt Apr 10, 2020
d0ba816
Merge branch 'master' into TaskCancellation
ijrsvt Apr 10, 2020
652a0fe
Fixing a few problems
ijrsvt Apr 10, 2020
daac610
Small problems
ijrsvt Apr 10, 2020
b050b28
Cleaning up
ijrsvt Apr 10, 2020
b0457a3
Response to changes
ijrsvt Apr 15, 2020
18b3dbc
Fixing error passing
ijrsvt Apr 15, 2020
b813faf
Merge branch 'master' into TaskCancellation
ijrsvt Apr 15, 2020
112d7d8
Merged to master
ijrsvt Apr 15, 2020
ff8bbd3
fixing lock
ijrsvt Apr 15, 2020
af35898
Cleaning up print statements
ijrsvt Apr 15, 2020
b015c51
Format
ijrsvt Apr 15, 2020
616f487
Fixing Unit test build failure
ijrsvt Apr 16, 2020
2361273
mock_worker fix
ijrsvt Apr 16, 2020
9dba915
java_fix
ijrsvt Apr 16, 2020
9a43056
Canel
ijrsvt Apr 16, 2020
68a6458
Switching to Cancel
ijrsvt Apr 17, 2020
46545e1
Responding to Review
ijrsvt Apr 21, 2020
7308225
FixFormatting
ijrsvt Apr 21, 2020
1f95492
Merge branch 'master' into TaskCancellation
ijrsvt Apr 21, 2020
9a0d120
Lease cancellation
ijrsvt Apr 22, 2020
82a6248
FInal comments?
ijrsvt Apr 22, 2020
3270f92
Moving exist check to CoreWorker
ijrsvt Apr 23, 2020
794f146
Fix Actor Transport Test
ijrsvt Apr 23, 2020
e43ea33
Fixing task manager test
ijrsvt Apr 23, 2020
9beea80
chaning clock repr
ijrsvt Apr 23, 2020
2a789f5
Fix build
ijrsvt Apr 24, 2020
8c75a83
fix white space
ijrsvt Apr 24, 2020
8f7bdfe
lint fix
ijrsvt Apr 24, 2020
6f1ef56
Updating to medium size
ijrsvt Apr 24, 2020
f7fb69f
Fixing Java test compilation issue
ijrsvt Apr 25, 2020
e8cd360
lengthen bad timeouts
ijrsvt Apr 25, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions python/ray/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
LOCAL_MODE,
SCRIPT_MODE,
WORKER_MODE,
cancel,
connect,
disconnect,
get,
Expand Down Expand Up @@ -113,6 +114,7 @@
"_config",
"_get_runtime_context",
"actor",
"cancel",
"connect",
"disconnect",
"get",
Expand Down
35 changes: 33 additions & 2 deletions python/ray/_raylet.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import logging
import os
import pickle
import sys
import _thread
import setproctitle

from libc.stdint cimport (
int32_t,
Expand Down Expand Up @@ -90,6 +92,7 @@ from ray.exceptions import (
RayTaskError,
ObjectStoreFullError,
RayTimeoutError,
RayCancellationError
)
from ray.utils import decode
import gc
Expand Down Expand Up @@ -452,14 +455,22 @@ cdef execute_task(
actor_title = "{}({}, {})".format(
class_name, repr(args), repr(kwargs))
core_worker.set_actor_title(actor_title.encode("utf-8"))
# Ensure no previous signals are still around
check_signals()
Copy link
Contributor

Choose a reason for hiding this comment

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

What signals is this checking for? If it's the keyboardinterrupt from interrupt_main, don't we need to catch that and handle it?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It was initially just to 'clear' any signals, but I can make it also handle cancellation.

# Execute the task.
with ray.worker._changeproctitle(title, next_title):
with core_worker.profile_event(b"task:execute"):
task_exception = True
outputs = function_executor(*args, **kwargs)
task_exception = False
try:
outputs = function_executor(*args, **kwargs)
task_exception = False
except KeyboardInterrupt as e:
Copy link
Contributor

Choose a reason for hiding this comment

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

Couldn't this get raised outside of the try block?

Copy link
Contributor

Choose a reason for hiding this comment

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

Yes, I believe this can be raised on any line of python code

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It can only be raised in regular python code. When in compiled Cython or C++ code, the interrupts can be observed with PyErr_CheckSignals (which check_signals does). As long as I call check_signals before python code (the next place it is called is in store_task_output, any lingering interrupts will be cleared.

raise RayCancellationError(
core_worker.get_current_task_id())
if c_return_ids.size() == 1:
outputs = (outputs,)
# Ensure no signals are still around
check_signals()
# Store the outputs in the object store.
with core_worker.profile_event(b"task:store_outputs"):
core_worker.store_task_outputs(
Expand Down Expand Up @@ -551,6 +562,14 @@ cdef void async_plasma_callback(CObjectID object_id,
event_handler._loop.call_soon_threadsafe(
event_handler._complete_future, obj_id)

cdef c_bool kill_main_task() nogil:
with gil:
if setproctitle.getproctitle() != "ray::IDLE":
_thread.interrupt_main()
return True
return False


cdef CRayStatus check_signals() nogil:
with gil:
try:
Expand Down Expand Up @@ -657,6 +676,7 @@ cdef class CoreWorker:
options.ref_counting_enabled = True
options.is_local_mode = local_mode
options.num_workers = 1
options.kill_main = kill_main_task

CCoreWorkerProcess.Initialize(options)

Expand Down Expand Up @@ -952,6 +972,17 @@ cdef class CoreWorker:
check_status(CCoreWorkerProcess.GetCoreWorker().KillActor(
c_actor_id, True, no_reconstruction))

def kill_task(self, ObjectID object_id, c_bool force_kill):
cdef:
CObjectID c_object_id = object_id.native()
CRayStatus status = CRayStatus.OK()

status = CCoreWorkerProcess.GetCoreWorker().KillTask(
c_object_id, force_kill)

if not status.ok():
raise ValueError(status.message().decode())

def resource_ids(self):
cdef:
ResourceMappingType resource_mapping = (
Expand Down
16 changes: 16 additions & 0 deletions python/ray/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,22 @@ class RayConnectionError(RayError):
pass


class RayCancellationError(RayError):
"""Raised when this task or a dependency is cancelled
Attributes:
task_id (TaskID): The TaskID of the function that was directly
cancelled.
"""

def __init__(self, task_id=None):
self.task_id = task_id

def __str__(self):
if self.task_id is None:
return "This task or its dependency was cancelled by"
return "Task: " + str(self.task_id) + " was cancelled"


class RayTaskError(RayError):
"""Indicates that a task threw an exception during execution.

Expand Down
2 changes: 2 additions & 0 deletions python/ray/includes/libcoreworker.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ cdef extern from "ray/core_worker/core_worker.h" nogil:
CRayStatus KillActor(
const CActorID &actor_id, c_bool force_kill,
c_bool no_reconstruction)
CRayStatus KillTask(const CObjectID &object_id, c_bool force_kill)

unique_ptr[CProfileEvent] CreateProfileEvent(
const c_string &event_type)
Expand Down Expand Up @@ -213,6 +214,7 @@ cdef extern from "ray/core_worker/core_worker.h" nogil:
c_bool ref_counting_enabled
c_bool is_local_mode
int num_workers
(c_bool() nogil) kill_main
CCoreWorkerOptions()

cdef cppclass CCoreWorkerProcess "ray::CoreWorkerProcess":
Expand Down
2 changes: 2 additions & 0 deletions python/ray/includes/unique_ids.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,8 @@ cdef extern from "ray/common/id.h" namespace "ray" nogil:
CTaskID ForNormalTask(CJobID job_id, CTaskID parent_task_id,
int64_t parent_task_counter)

CActorID ActorId() const

cdef cppclass CObjectID" ray::ObjectID"(CBaseID[CObjectID]):

@staticmethod
Expand Down
3 changes: 3 additions & 0 deletions python/ray/includes/unique_ids.pxi
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,9 @@ cdef class TaskID(BaseID):
def is_nil(self):
return self.data.IsNil()

def actor_id(self):
return ActorID(self.data.ActorId().Binary())

cdef size_t hash(self):
return self.data.Hash()

Expand Down
3 changes: 3 additions & 0 deletions python/ray/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
PlasmaObjectNotAvailable,
RayTaskError,
RayActorError,
RayCancellationError,
RayWorkerError,
UnreconstructableError,
)
Expand Down Expand Up @@ -279,6 +280,8 @@ def _deserialize_object(self, data, metadata, object_id):
return RayWorkerError()
elif error_type == ErrorType.Value("ACTOR_DIED"):
return RayActorError()
elif error_type == ErrorType.Value("TASK_CANCELLED"):
return RayCancellationError()
elif error_type == ErrorType.Value("OBJECT_UNRECONSTRUCTABLE"):
return UnreconstructableError(ray.ObjectID(object_id.binary()))
else:
Expand Down
8 changes: 8 additions & 0 deletions python/ray/tests/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -414,3 +414,11 @@ py_test(
tags = ["exclusive"],
deps = ["//:ray_lib"],
)

py_test(
name = "test_cancel",
size = "small",
srcs = ["test_cancel.py],
tags = ["exclusive"],
deps = ["//:ray_lib"],
)
191 changes: 191 additions & 0 deletions python/ray/tests/test_cancel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
import pytest
import ray
import random
import sys
import time
from ray.exceptions import RayTaskError, RayTimeoutError, RayCancellationError
from ray.test_utils import SignalActor


@pytest.mark.parametrize("use_force", [True, False])
def test_cancel_chain(ray_start_regular, use_force):
"""A helper method for chain of events tests"""
signaler = SignalActor.remote()

@ray.remote
def wait_for(t):
return ray.get(t[0])

obj1 = wait_for.remote([signaler.wait.remote()])
obj2 = wait_for.remote([obj1])
obj3 = wait_for.remote([obj2])
obj4 = wait_for.remote([obj3])

assert len(ray.wait([obj1], timeout=.1)[0]) == 0
ray.cancel(obj1, use_force)
for ob in [obj1, obj2, obj3, obj4]:
with pytest.raises((RayTaskError, RayCancellationError)):
ray.get(ob)

signaler2 = SignalActor.remote()
obj1 = wait_for.remote([signaler2.wait.remote()])
obj2 = wait_for.remote([obj1])
obj3 = wait_for.remote([obj2])
obj4 = wait_for.remote([obj3])

assert len(ray.wait([obj3], timeout=.1)[0]) == 0
ray.cancel(obj3, use_force)
for ob in [obj3, obj4]:
with pytest.raises((RayTaskError, RayCancellationError)):
ray.get(ob)

with pytest.raises(RayTimeoutError):
ray.get(obj1, timeout=.1)

with pytest.raises(RayTimeoutError):
ray.get(obj2, timeout=.1)

signaler2.send.remote()
ray.get(obj1, timeout=.1)


@pytest.mark.parametrize("use_force", [True, False])
def test_cancel_multiple_dependents(ray_start_regular, use_force):
"""A helper method for multiple waiters on events tests"""
signaler = SignalActor.remote()

@ray.remote
def wait_for(t):
return ray.get(t[0])

head = wait_for.remote([signaler.wait.remote()])
deps = []
for _ in range(3):
deps.append(wait_for.remote([head]))

assert len(ray.wait([head], timeout=.1)[0]) == 0
ray.cancel(head, use_force)
for d in deps:
with pytest.raises((RayTaskError, RayCancellationError)):
ray.get(d)

head2 = wait_for.remote([signaler.wait.remote()])

deps2 = []
for _ in range(3):
deps2.append(wait_for.remote([head]))

for d in deps2:
ray.cancel(d, use_force)

for d in deps2:
with pytest.raises((RayTaskError, RayCancellationError)):
ray.get(d)

signaler.send.remote()
ray.get(head2, timeout=1)


@pytest.mark.parametrize("use_force", [True, False])
def test_single_cpu_cancel(shutdown_only, use_force):
ray.init(num_cpus=1)
signaler = SignalActor.remote()

@ray.remote
def wait_for(t):
return ray.get(t[0])

obj1 = wait_for.remote([signaler.wait.remote()])
obj2 = wait_for.remote([obj1])
obj3 = wait_for.remote([obj2])
indep = wait_for.remote([signaler.wait.remote()])

assert len(ray.wait([obj3], timeout=.1)[0]) == 0
ray.cancel(obj3, use_force)
with pytest.raises((RayTaskError, RayCancellationError)):
ray.get(obj3, 0.1)

ray.cancel(obj1, use_force)

for d in [obj1, obj2]:
with pytest.raises((RayTaskError, RayCancellationError)):
ray.get(d)

signaler.send.remote()
ray.get(indep)


@pytest.mark.parametrize("use_force", [True, False])
def test_comprehensive(ray_start_regular, use_force):
signaler = SignalActor.remote()

@ray.remote
def wait_for(t):
ray.get(t[0])
return "Result"

@ray.remote
def combine(a, b):
return str(a) + str(b)

a = wait_for.remote([signaler.wait.remote()])
b = wait_for.remote([signaler.wait.remote()])
combo = combine.remote(a, b)
a2 = wait_for.remote([a])

assert len(ray.wait([a, b, a2, combo], timeout=1)[0]) == 0

ray.cancel(a, use_force)
with pytest.raises((RayTaskError, RayCancellationError)):
ray.get(a, 1)

with pytest.raises((RayTaskError, RayCancellationError)):
ray.get(a2, 1)

signaler.send.remote()

with pytest.raises((RayTaskError, RayCancellationError)):
ray.get(combo, 10)


@pytest.mark.parametrize("use_force", [True, False])
def test_stress(shutdown_only, use_force):
ray.init(num_cpus=1)

@ray.remote
def infinite_sleep(y):
if y:
while True:
time.sleep(1 / 10)

first = infinite_sleep.remote(True)

sleep_or_no = [random.randint(0, 1) for _ in range(100)]
tasks = [infinite_sleep.remote(i) for i in sleep_or_no]
cancelled = set()
for t in tasks:
if random.random() > 0.5:
ray.cancel(t, use_force)
cancelled.add(t)

ray.cancel(first, use_force)
cancelled.add(first)

for done in cancelled:
with pytest.raises((RayTaskError, RayCancellationError)):
ray.get(done, 10)

for indx in range(len(tasks)):
t = tasks[indx]
if sleep_or_no[indx]:
ray.cancel(t, use_force)
cancelled.add(t)
if t in cancelled:
with pytest.raises((RayTaskError, RayCancellationError)):
ray.get(t, 10)
else:
ray.get(t)


if __name__ == "__main__":
sys.exit(pytest.main(["-v", __file__]))
Loading