Repository: celery/celery

Issue:
[Celery 4.3] when result_extended=True task name is always None
<!--
Please fill this template entirely and do not erase parts of it.
We reserve the right to close without a response
bug reports which are incomplete.
-->
# Checklist
<!--
To check an item on the list replace [ ] with [x].
-->

- [x] I have read the relevant section in the
  [contribution guide](http://docs.celeryproject.org/en/latest/contributing.html#other-bugs)
  on reporting bugs.
- [x] I have checked the [issues list](https://github.com/celery/celery/issues?q=is%3Aissue+label%3A%22Issue+Type%3A+Bug+Report%22+-label%3A%22Category%3A+Documentation%22)
  for similar or identical bug reports.
- [x] I have checked the [pull requests list](https://github.com/celery/celery/pulls?q=is%3Apr+label%3A%22PR+Type%3A+Bugfix%22+-label%3A%22Category%3A+Documentation%22)
  for existing proposed fixes.
- [x] I have checked the [commit log](https://github.com/celery/celery/commits/master)
  to find out if the bug was already fixed in the master branch.
- [x] I have included all related issues and possible duplicate issues
  in this issue (If there are none, check this box anyway).

## Mandatory Debugging Information

- [ ] I have included the output of ``celery -A proj report`` in the issue.
    (if you are not able to do this, then at least specify the Celery
     version affected).
- [x] I have verified that the issue exists against the `master` branch of Celery.
- [ ] I have included the contents of ``pip freeze`` in the issue.
- [ ] I have included all the versions of all the external dependencies required
  to reproduce this bug.

## Optional Debugging Information
<!--
Try some of the below if you think they are relevant.
It will help us figure out the scope of the bug and how many users it affects.
-->
- [ ] I have tried reproducing the issue on more than one Python version
  and/or implementation.
- [ ] I have tried reproducing the issue on more than one message broker and/or
  result backend.
- [ ] I have tried reproducing the issue on more than one version of the message
  broker and/or result backend.
- [ ] I have tried reproducing the issue on more than one operating system.
- [ ] I have tried reproducing the issue on more than one workers pool.
- [ ] I have tried reproducing the issue with autoscaling, retries,
  ETA/Countdown & rate limits disabled.
- [ ] I have tried reproducing the issue after downgrading
  and/or upgrading Celery and its dependencies.

## Related Issues and Possible Duplicates
<!--
Please make sure to search and mention any related issues
or possible duplicates to this issue as requested by the checklist above.

This may or may not include issues in other repositories that the Celery project
maintains or other repositories that are dependencies of Celery.

If you don't know how to mention issues, please refer to Github's documentation
on the subject: https://help.github.com/en/articles/autolinked-references-and-urls#issues-and-pull-requests
-->

#### Related Issues

- None

#### Possible Duplicates

- None

## Environment & Settings
<!-- Include the contents of celery --version below -->
**Celery version**:
<!-- Include the output of celery -A proj report below -->
<details>
<summary><b><code>celery report</code> Output:</b></summary>
<p>

```
```

</p>
</details>

# Steps to Reproduce

## Required Dependencies
<!-- Please fill the required dependencies to reproduce this issue -->
* **Minimal Python Version**: N/A or Unknown
* **Minimal Celery Version**: N/A or Unknown
* **Minimal Kombu Version**: N/A or Unknown
* **Minimal Broker Version**: N/A or Unknown
* **Minimal Result Backend Version**: N/A or Unknown
* **Minimal OS and/or Kernel Version**: N/A or Unknown
* **Minimal Broker Client Version**: N/A or Unknown
* **Minimal Result Backend Client Version**: N/A or Unknown

### Python Packages
<!-- Please fill the contents of pip freeze below -->
<details>
<summary><b><code>pip freeze</code> Output:</b></summary>
<p>

```
```

</p>
</details>

### Other Dependencies
<!--
Please provide system dependencies, configuration files
and other dependency information if applicable
-->
<details>
<p>
N/A
</p>
</details>

## Minimally Reproducible Test Case
<!--
Please provide a reproducible test case.
Refer to the Reporting Bugs section in our contribution guide.

We prefer submitting test cases in the form of a PR to our integration test suite.
If you can provide one, please mention the PR number below.
If not, please attach the most minimal code example required to reproduce the issue below.
If the test case is too large, please include a link to a gist or a repository below.
-->

<details>
<p>

```python
```

</p>
</details>

# Expected Behavior
When `result_extended` is set to `True`, we expect to get the task name using the `name` attribute. 

# Actual Behavior
The `name` is always `None`, after debugging the `Context` object that is being passed to `BaseKeyValueStoreBackend.store_result` it contains the task name with the attribute `task` and not `task_name` as `BaseKeyValueStoreBackend._store_result` is trying to get from the request object:

```python
if self.app.conf.find_value_for_key('extended', 'result'):
    if request:
        request_meta = {
            'name': getattr(request, 'task_name', None),
            'args': getattr(request, 'args', None),
            'kwargs': getattr(request, 'kwargs', None),
            'worker': getattr(request, 'hostname', None),
            'retries': getattr(request, 'retries', None),
            'queue': request.delivery_info.get('routing_key')
            if hasattr(request, 'delivery_info') and
            request.delivery_info else None
        }

        meta.update(request_meta)
```

Also the unit test `test_result.test_AsyncResult.test_get_request_meta` is using a `Context` object with an explicit `task_name` set.


Discussion:
Hi @johnarnold, I'm pinging you since you contributed the original PR.
It seems like `task_name` is not properly initialized. Do you have an idea why?
@thedrow Ouch. I swear I tested for task name and had it working with flower. I'll take a look.
Found:  https://github.com/celery/celery/blob/master/celery/app/task.py#L95
Hi,

I'm facing the same issue. I'm not familiarized with the source code but I wanted to share what I found while trying to understand how everything works.

The message sent to the worker has the task name under the key `'task'`. See:

- https://github.com/celery/celery/blob/master/celery/app/amqp.py#L353 (protocol v2)
- https://github.com/celery/celery/blob/master/celery/app/amqp.py#L433 (protocol v1)

In fact, the consumer fails otherwise. See:

- https://github.com/celery/celery/blob/master/celery/worker/consumer/consumer.py#L546 (protocol v2)
- https://github.com/celery/celery/blob/master/celery/worker/consumer/consumer.py#L555 (protocol v1)

Using that same message format, a `Request` object is created. See:

- https://github.com/celery/celery/blob/b2668607c909c61becd151905b4525190c19ff4a/celery/worker/strategy.py#L149

The `Context` class is initialized using that request dict. See:

- https://github.com/celery/celery/blob/b2668607c909c61becd151905b4525190c19ff4a/celery/worker/request.py#L523
- https://github.com/celery/celery/blob/4d4fb3bf04ebf1642428dccdd578f2f244aa158f/celery/app/trace.py#L365

Since the request dict has the task name under the key `'task'` (not `'task_name'`), the `Context` object has the task name in the attribute `'task'` as well. See:

- https://github.com/celery/celery/blob/master/celery/app/task.py#L100
- https://github.com/celery/celery/blob/master/celery/app/task.py#L103

It seems that using `task` instead of `task_name` in `BaseKeyValueStoreBackend._store_result` should fix this. Of course, the attribute in the `Context` class should be changed as well:

- https://github.com/celery/celery/blob/master/celery/app/task.py#L95
- https://github.com/celery/celery/blob/master/celery/app/task.py#L132

I hope it helps!
@svidela thank you for the explanation, that's what I was saying, the request object has a `task` attribute and not a `task_name`,  the tests pass because a `Context` object is explicitly set with `task_name`.

Resolving patch:
diff --git a/celery/app/task.py b/celery/app/task.py
--- a/celery/app/task.py
+++ b/celery/app/task.py
@@ -92,7 +92,6 @@ class Context(object):
     errbacks = None
     timelimit = None
     origin = None
-    task_name = None
     _children = None   # see property
     _protected = 0
 
@@ -129,7 +128,6 @@ def as_execution_options(self):
             'retries': self.retries,
             'reply_to': self.reply_to,
             'origin': self.origin,
-            'task_name': self.task_name
         }
 
     @property
diff --git a/celery/backends/base.py b/celery/backends/base.py
--- a/celery/backends/base.py
+++ b/celery/backends/base.py
@@ -699,7 +699,7 @@ def _store_result(self, task_id, result, state,
         if self.app.conf.find_value_for_key('extended', 'result'):
             if request:
                 request_meta = {
-                    'name': getattr(request, 'task_name', None),
+                    'name': getattr(request, 'task', None),
                     'args': getattr(request, 'args', None),
                     'kwargs': getattr(request, 'kwargs', None),
                     'worker': getattr(request, 'hostname', None),


Test patch:
diff --git a/t/unit/tasks/test_result.py b/t/unit/tasks/test_result.py
--- a/t/unit/tasks/test_result.py
+++ b/t/unit/tasks/test_result.py
@@ -408,7 +408,7 @@ def test_get_request_meta(self):
 
         x = self.app.AsyncResult('1')
         request = Context(
-            task_name='foo',
+            task='foo',
             children=None,
             args=['one', 'two'],
             kwargs={'kwarg1': 'three'},