We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Request on_timeout should ignore soft time limit exception
When Request.on_timeout receive a soft timeout from billiard, it does the same as if it was receiving a hard time limit exception. This is ran by the controller.

But the task may catch this exception and eg. return (this is what soft timeout are for).

This cause:
1. the result to be saved once as an exception by the controller (on_timeout) and another time with the result returned by the task
2. the task status to be passed to failure and to success on the same manner
3. if the task is participating to a chord, the chord result counter (at least with redis) is incremented twice (instead of once), making the chord to return prematurely and eventually loose tasks…

1, 2 and 3 can leads of course to strange race conditions…

## Steps to reproduce (Illustration)

with the program in test_timeout.py:

```python
import time
import celery


app = celery.Celery('test_timeout')
app.conf.update(
    result_backend="redis://localhost/0",
    broker_url="amqp://celery:celery@localhost:5672/host",
)

@app.task(soft_time_limit=1)
def test():
    try:
        time.sleep(2)
    except Exception:
        return 1

@app.task()
def add(args):
    print("### adding", args)
    return sum(args)

@app.task()
def on_error(context, exception, traceback, **kwargs):
    print("### on_error: ", exception)

if __name__ == "__main__":
    result = celery.chord([test.s().set(link_error=on_error.s()), test.s().set(link_error=on_error.s())])(add.s())
    result.get()
```

start a worker and the program:

```
$ celery -A test_timeout worker -l WARNING
$ python3 test_timeout.py
```

## Expected behavior

add method is called with `[1, 1]` as argument and test_timeout.py return normally

## Actual behavior

The test_timeout.py fails, with
```
celery.backends.base.ChordError: Callback error: ChordError("Dependency 15109e05-da43-449f-9081-85d839ac0ef2 raised SoftTimeLimitExceeded('SoftTimeLimitExceeded(True,)',)",
```
On the worker side, the **on_error is called but the add method as well !**

```
[2017-11-29 23:07:25,538: WARNING/MainProcess] Soft time limit (1s) exceeded for test_timeout.test[15109e05-da43-449f-9081-85d839ac0ef2]
[2017-11-29 23:07:25,546: WARNING/MainProcess] ### on_error:
[2017-11-29 23:07:25,546: WARNING/MainProcess] SoftTimeLimitExceeded(True,)
[2017-11-29 23:07:25,547: WARNING/MainProcess] Soft time limit (1s) exceeded for test_timeout.test[38f3f7f2-4a89-4318-8ee9-36a987f73757]
[2017-11-29 23:07:25,553: ERROR/MainProcess] Chord callback for 'ef6d7a38-d1b4-40ad-b937-ffa84e40bb23' raised: ChordError("Dependency 15109e05-da43-449f-9081-85d839ac0ef2 raised SoftTimeLimitExceeded('SoftTimeLimitExceeded(True,)',)",)
Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/celery/backends/redis.py", line 290, in on_chord_part_return
    callback.delay([unpack(tup, decode) for tup in resl])
  File "/usr/local/lib/python3.4/dist-packages/celery/backends/redis.py", line 290, in <listcomp>
    callback.delay([unpack(tup, decode) for tup in resl])
  File "/usr/local/lib/python3.4/dist-packages/celery/backends/redis.py", line 243, in _unpack_chord_result
    raise ChordError('Dependency {0} raised {1!r}'.format(tid, retval))
celery.exceptions.ChordError: Dependency 15109e05-da43-449f-9081-85d839ac0ef2 raised SoftTimeLimitExceeded('SoftTimeLimitExceeded(True,)',)
[2017-11-29 23:07:25,565: WARNING/MainProcess] ### on_error:
[2017-11-29 23:07:25,565: WARNING/MainProcess] SoftTimeLimitExceeded(True,)
[2017-11-29 23:07:27,262: WARNING/PoolWorker-2] ### adding
[2017-11-29 23:07:27,264: WARNING/PoolWorker-2] [1, 1]
```

Of course, on purpose did I choose to call the test.s() twice, to show that the count in the chord continues. In fact:
- the chord result is incremented twice by the error of soft time limit
- the chord result is again incremented twice by the correct returning of `test` task

## Conclusion

Request.on_timeout  should not process soft time limit exception. 

here is a quick monkey patch (correction of celery is trivial)

```python
def patch_celery_request_on_timeout():
    from celery.worker import request
    orig = request.Request.on_timeout
    def patched_on_timeout(self, soft, timeout):
        if not soft:
            orig(self, soft, timeout)
    request.Request.on_timeout = patched_on_timeout
patch_celery_request_on_timeout()
```



## version info

software -> celery:4.1.0 (latentcall) kombu:4.0.2 py:3.4.3
            billiard:3.5.0.2 py-amqp:2.1.4
platform -> system:Linux arch:64bit, ELF imp:CPython
loader   -> celery.loaders.app.AppLoader
settings -> transport:amqp results:redis://10.0.3.253/0


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `celery/app/registry.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 """Registry of available tasks."""
3 from __future__ import absolute_import, unicode_literals
4 import inspect
5 from importlib import import_module
6 from celery._state import get_current_app
7 from celery.exceptions import NotRegistered
8 from celery.five import items
9 
10 __all__ = ['TaskRegistry']
11 
12 
13 class TaskRegistry(dict):
14     """Map of registered tasks."""
15 
16     NotRegistered = NotRegistered
17 
18     def __missing__(self, key):
19         raise self.NotRegistered(key)
20 
21     def register(self, task):
22         """Register a task in the task registry.
23 
24         The task will be automatically instantiated if not already an
25         instance.
26         """
27         self[task.name] = inspect.isclass(task) and task() or task
28 
29     def unregister(self, name):
30         """Unregister task by name.
31 
32         Arguments:
33             name (str): name of the task to unregister, or a
34                 :class:`celery.task.base.Task` with a valid `name` attribute.
35 
36         Raises:
37             celery.exceptions.NotRegistered: if the task is not registered.
38         """
39         try:
40             self.pop(getattr(name, 'name', name))
41         except KeyError:
42             raise self.NotRegistered(name)
43 
44     # -- these methods are irrelevant now and will be removed in 4.0
45     def regular(self):
46         return self.filter_types('regular')
47 
48     def periodic(self):
49         return self.filter_types('periodic')
50 
51     def filter_types(self, type):
52         return {name: task for name, task in items(self)
53                 if getattr(task, 'type', 'regular') == type}
54 
55 
56 def _unpickle_task(name):
57     return get_current_app().tasks[name]
58 
59 
60 def _unpickle_task_v2(name, module=None):
61     if module:
62         import_module(module)
63     return get_current_app().tasks[name]
64
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/celery/app/registry.py b/celery/app/registry.py
--- a/celery/app/registry.py
+++ b/celery/app/registry.py
@@ -4,7 +4,7 @@
 import inspect
 from importlib import import_module
 from celery._state import get_current_app
-from celery.exceptions import NotRegistered
+from celery.exceptions import NotRegistered, InvalidTaskError
 from celery.five import items
 
 __all__ = ['TaskRegistry']
@@ -22,8 +22,10 @@
         """Register a task in the task registry.
 
         The task will be automatically instantiated if not already an
-        instance.
+        instance. Name must be configured prior to registration.
         """
+        if task.name is None:
+            raise InvalidTaskError('Task "class {0}" must specify name'.format(task.__class__.__name__))
         self[task.name] = inspect.isclass(task) and task() or task
 
     def unregister(self, name):

{"golden_diff": "diff --git a/celery/app/registry.py b/celery/app/registry.py\n--- a/celery/app/registry.py\n+++ b/celery/app/registry.py\n@@ -4,7 +4,7 @@\n import inspect\n from importlib import import_module\n from celery._state import get_current_app\n-from celery.exceptions import NotRegistered\n+from celery.exceptions import NotRegistered, InvalidTaskError\n from celery.five import items\n \n __all__ = ['TaskRegistry']\n@@ -22,8 +22,10 @@\n         \"\"\"Register a task in the task registry.\n \n         The task will be automatically instantiated if not already an\n-        instance.\n+        instance. Name must be configured prior to registration.\n         \"\"\"\n+        if task.name is None:\n+            raise InvalidTaskError('Task \"class {0}\" must specify name'.format(task.__class__.__name__))\n         self[task.name] = inspect.isclass(task) and task() or task\n \n     def unregister(self, name):\n", "issue": "Request on_timeout should ignore soft time limit exception\nWhen Request.on_timeout receive a soft timeout from billiard, it does the same as if it was receiving a hard time limit exception. This is ran by the controller.\r\n\r\nBut the task may catch this exception and eg. return (this is what soft timeout are for).\r\n\r\nThis cause:\r\n1. the result to be saved once as an exception by the controller (on_timeout) and another time with the result returned by the task\r\n2. the task status to be passed to failure and to success on the same manner\r\n3. if the task is participating to a chord, the chord result counter (at least with redis) is incremented twice (instead of once), making the chord to return prematurely and eventually loose tasks\u2026\r\n\r\n1, 2 and 3 can leads of course to strange race conditions\u2026\r\n\r\n## Steps to reproduce (Illustration)\r\n\r\nwith the program in test_timeout.py:\r\n\r\n```python\r\nimport time\r\nimport celery\r\n\r\n\r\napp = celery.Celery('test_timeout')\r\napp.conf.update(\r\n    result_backend=\"redis://localhost/0\",\r\n    broker_url=\"amqp://celery:celery@localhost:5672/host\",\r\n)\r\n\r\n@app.task(soft_time_limit=1)\r\ndef test():\r\n    try:\r\n        time.sleep(2)\r\n    except Exception:\r\n        return 1\r\n\r\n@app.task()\r\ndef add(args):\r\n    print(\"### adding\", args)\r\n    return sum(args)\r\n\r\n@app.task()\r\ndef on_error(context, exception, traceback, **kwargs):\r\n    print(\"### on_error:\u00a0\", exception)\r\n\r\nif __name__ == \"__main__\":\r\n    result = celery.chord([test.s().set(link_error=on_error.s()), test.s().set(link_error=on_error.s())])(add.s())\r\n    result.get()\r\n```\r\n\r\nstart a worker and the program:\r\n\r\n```\r\n$ celery -A test_timeout worker -l WARNING\r\n$ python3 test_timeout.py\r\n```\r\n\r\n## Expected behavior\r\n\r\nadd method is called with `[1, 1]` as argument and test_timeout.py return normally\r\n\r\n## Actual behavior\r\n\r\nThe test_timeout.py fails, with\r\n```\r\ncelery.backends.base.ChordError: Callback error: ChordError(\"Dependency 15109e05-da43-449f-9081-85d839ac0ef2 raised SoftTimeLimitExceeded('SoftTimeLimitExceeded(True,)',)\",\r\n```\r\nOn the worker side, the **on_error is called but the add method as well !**\r\n\r\n```\r\n[2017-11-29 23:07:25,538: WARNING/MainProcess] Soft time limit (1s) exceeded for test_timeout.test[15109e05-da43-449f-9081-85d839ac0ef2]\r\n[2017-11-29 23:07:25,546: WARNING/MainProcess] ### on_error:\r\n[2017-11-29 23:07:25,546: WARNING/MainProcess] SoftTimeLimitExceeded(True,)\r\n[2017-11-29 23:07:25,547: WARNING/MainProcess] Soft time limit (1s) exceeded for test_timeout.test[38f3f7f2-4a89-4318-8ee9-36a987f73757]\r\n[2017-11-29 23:07:25,553: ERROR/MainProcess] Chord callback for 'ef6d7a38-d1b4-40ad-b937-ffa84e40bb23' raised: ChordError(\"Dependency 15109e05-da43-449f-9081-85d839ac0ef2 raised SoftTimeLimitExceeded('SoftTimeLimitExceeded(True,)',)\",)\r\nTraceback (most recent call last):\r\n  File \"/usr/local/lib/python3.4/dist-packages/celery/backends/redis.py\", line 290, in on_chord_part_return\r\n    callback.delay([unpack(tup, decode) for tup in resl])\r\n  File \"/usr/local/lib/python3.4/dist-packages/celery/backends/redis.py\", line 290, in <listcomp>\r\n    callback.delay([unpack(tup, decode) for tup in resl])\r\n  File \"/usr/local/lib/python3.4/dist-packages/celery/backends/redis.py\", line 243, in _unpack_chord_result\r\n    raise ChordError('Dependency {0} raised {1!r}'.format(tid, retval))\r\ncelery.exceptions.ChordError: Dependency 15109e05-da43-449f-9081-85d839ac0ef2 raised SoftTimeLimitExceeded('SoftTimeLimitExceeded(True,)',)\r\n[2017-11-29 23:07:25,565: WARNING/MainProcess] ### on_error:\r\n[2017-11-29 23:07:25,565: WARNING/MainProcess] SoftTimeLimitExceeded(True,)\r\n[2017-11-29 23:07:27,262: WARNING/PoolWorker-2] ### adding\r\n[2017-11-29 23:07:27,264: WARNING/PoolWorker-2] [1, 1]\r\n```\r\n\r\nOf course, on purpose did I choose to call the test.s() twice, to show that the count in the chord continues. In fact:\r\n- the chord result is incremented twice by the error of soft time limit\r\n- the chord result is again incremented twice by the correct returning of `test` task\r\n\r\n## Conclusion\r\n\r\nRequest.on_timeout  should not process soft time limit exception. \r\n\r\nhere is a quick monkey patch (correction of celery is trivial)\r\n\r\n```python\r\ndef patch_celery_request_on_timeout():\r\n    from celery.worker import request\r\n    orig = request.Request.on_timeout\r\n    def patched_on_timeout(self, soft, timeout):\r\n        if not soft:\r\n            orig(self, soft, timeout)\r\n    request.Request.on_timeout = patched_on_timeout\r\npatch_celery_request_on_timeout()\r\n```\r\n\r\n\r\n\r\n## version info\r\n\r\nsoftware -> celery:4.1.0 (latentcall) kombu:4.0.2 py:3.4.3\r\n            billiard:3.5.0.2 py-amqp:2.1.4\r\nplatform -> system:Linux arch:64bit, ELF imp:CPython\r\nloader   -> celery.loaders.app.AppLoader\r\nsettings -> transport:amqp results:redis://10.0.3.253/0\r\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"Registry of available tasks.\"\"\"\nfrom __future__ import absolute_import, unicode_literals\nimport inspect\nfrom importlib import import_module\nfrom celery._state import get_current_app\nfrom celery.exceptions import NotRegistered\nfrom celery.five import items\n\n__all__ = ['TaskRegistry']\n\n\nclass TaskRegistry(dict):\n    \"\"\"Map of registered tasks.\"\"\"\n\n    NotRegistered = NotRegistered\n\n    def __missing__(self, key):\n        raise self.NotRegistered(key)\n\n    def register(self, task):\n        \"\"\"Register a task in the task registry.\n\n        The task will be automatically instantiated if not already an\n        instance.\n        \"\"\"\n        self[task.name] = inspect.isclass(task) and task() or task\n\n    def unregister(self, name):\n        \"\"\"Unregister task by name.\n\n        Arguments:\n            name (str): name of the task to unregister, or a\n                :class:`celery.task.base.Task` with a valid `name` attribute.\n\n        Raises:\n            celery.exceptions.NotRegistered: if the task is not registered.\n        \"\"\"\n        try:\n            self.pop(getattr(name, 'name', name))\n        except KeyError:\n            raise self.NotRegistered(name)\n\n    # -- these methods are irrelevant now and will be removed in 4.0\n    def regular(self):\n        return self.filter_types('regular')\n\n    def periodic(self):\n        return self.filter_types('periodic')\n\n    def filter_types(self, type):\n        return {name: task for name, task in items(self)\n                if getattr(task, 'type', 'regular') == type}\n\n\ndef _unpickle_task(name):\n    return get_current_app().tasks[name]\n\n\ndef _unpickle_task_v2(name, module=None):\n    if module:\n        import_module(module)\n    return get_current_app().tasks[name]\n", "path": "celery/app/registry.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"Registry of available tasks.\"\"\"\nfrom __future__ import absolute_import, unicode_literals\nimport inspect\nfrom importlib import import_module\nfrom celery._state import get_current_app\nfrom celery.exceptions import NotRegistered, InvalidTaskError\nfrom celery.five import items\n\n__all__ = ['TaskRegistry']\n\n\nclass TaskRegistry(dict):\n    \"\"\"Map of registered tasks.\"\"\"\n\n    NotRegistered = NotRegistered\n\n    def __missing__(self, key):\n        raise self.NotRegistered(key)\n\n    def register(self, task):\n        \"\"\"Register a task in the task registry.\n\n        The task will be automatically instantiated if not already an\n        instance. Name must be configured prior to registration.\n        \"\"\"\n        if task.name is None:\n            raise InvalidTaskError('Task \"class {0}\" must specify name'.format(task.__class__.__name__))\n        self[task.name] = inspect.isclass(task) and task() or task\n\n    def unregister(self, name):\n        \"\"\"Unregister task by name.\n\n        Arguments:\n            name (str): name of the task to unregister, or a\n                :class:`celery.task.base.Task` with a valid `name` attribute.\n\n        Raises:\n            celery.exceptions.NotRegistered: if the task is not registered.\n        \"\"\"\n        try:\n            self.pop(getattr(name, 'name', name))\n        except KeyError:\n            raise self.NotRegistered(name)\n\n    # -- these methods are irrelevant now and will be removed in 4.0\n    def regular(self):\n        return self.filter_types('regular')\n\n    def periodic(self):\n        return self.filter_types('periodic')\n\n    def filter_types(self, type):\n        return {name: task for name, task in items(self)\n                if getattr(task, 'type', 'regular') == type}\n\n\ndef _unpickle_task(name):\n    return get_current_app().tasks[name]\n\n\ndef _unpickle_task_v2(name, module=None):\n    if module:\n        import_module(module)\n    return get_current_app().tasks[name]\n", "path": "celery/app/registry.py"}]}