Repository: celery/celery (Python)

Issue:
chord_unlock isn't using the same queue as chord body task
<!--
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 verified that the issue exists against the `master` branch of Celery.
- [ ] This has already been asked to the [discussion group](https://groups.google.com/forum/#!forum/celery-users) first.
- [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

- [x] 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.
-->
- [x] I have tried reproducing the issue on more than one Python version
  and/or implementation.
- [x] I have tried reproducing the issue on more than one message broker and/or
  result backend.
- [x] I have tried reproducing the issue on more than one version of the message
  broker and/or result backend.
- [x] I have tried reproducing the issue on more than one operating system.
- [x] 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.
- [x] 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

https://github.com/celery/celery/issues/4337 -- closed duplicate, partially fixed with https://github.com/celery/celery/pull/4448 for manual routing (explicitly passing queue name in signature parameters).

## 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>

```
celery -A myapp report

software -> celery:5.1.2 (sun-harmonics) kombu:5.1.0 py:3.9.5
            billiard:3.6.4.0 py-amqp:5.0.6
platform -> system:Darwin arch:64bit
            kernel version:20.6.0 imp:CPython
loader   -> celery.loaders.app.AppLoader
settings -> transport:amqp results:db+postgresql://postgres:**@postgres:5432/postgres

broker_url: 'amqp://guest:********@localhost:5672//'
result_backend: 'db+postgresql://postgres:********@postgres:5432/postgres'
task_routes: 
    ({'*': {'queue': 'low_priority_queue'},
  'myapp.add_list': {'queue': 'high_priority_queue'}},)
deprecated_settings: None
```

</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>


`celeryconfig.py`
```python
broker_url = "amqp://guest@localhost//"
result_backend = 'db+postgresql://{user}:{password}@{host}:{port}/{db}'.format(
    user='postgres',
    password='secretsecret',
    host='postgres',
    db='postgres',
    port=5432,
)

task_routes = ({
    "myapp.add_list": {"queue": "high_priority_queue"},
    "*": {"queue": "low_priority_queue"},
},)

```


`myapp.py`
```
from celery import Celery

app = Celery('myapp')
app.config_from_object("celeryconfig")


@app.task
def add_list(args):
    return sum(args)


if __name__ == '__main__':
    app.start()
```

`main.py`
```
from myapp import add_list, app
from celery.canvas import chord

app.config_from_object("celeryconfig")
promise = chord([add_list.s([2, 3]), add_list.s([4, 5])])(add_list.s())
print(promise.get())
```


</p>
</details>

**Steps to reproduce**:

1. Execute `docker run -d -p 5672:5672 rabbitmq` to start broker
2. Execute `docker run -d -p 5432:5432 postgres:11.4` for backend.
3. Run first worker with `celery -A myapp worker -l debug -Q high_priority_queue` in first terminal window
4. Run second worker with `celery -A myapp worker -l debug -Q low_priority_queue` in second terminal window
5. Run python3 -m main in third terminal window


# Expected Behavior
<!-- Describe in detail what you expect to happen -->
All the tasks are routed to `high_priority_queue` and executed by the first worker.

# Actual Behavior
`celery.chord_unlock` task is routed to the default `low_priority_queue` and executed by the second worker.
 
<!--
Describe in detail what actually happened.
Please include a backtrace and surround it with triple backticks (```).
In addition, include the Celery daemon logs, the broker logs,
the result backend logs and system logs below if they will help us debug
the issue.
-->



Discussion:
Hey @MelnykR :wave:,
Thank you for opening an issue. We will get back to you as soon as we can.
Also, check out our [Open Collective](https://opencollective.com/celery) and consider backing us - every little helps!

We also offer priority support for our sponsors.
If you require immediate assistance please consider sponsoring us.




Patch:
diff --git a/celery/backends/base.py b/celery/backends/base.py
index 4ad6de4697b..f6bc458711b 100644
--- a/celery/backends/base.py
+++ b/celery/backends/base.py
@@ -650,6 +650,12 @@ def fallback_chord_unlock(self, header_result, body, countdown=1,
             body_type = None
 
         queue = body.options.get('queue', getattr(body_type, 'queue', None))
+
+        if queue is None:
+            # fallback to default routing if queue name was not
+            # explicitly passed to body callback
+            queue = self.app.amqp.router.route(kwargs, body.name)['queue'].name
+
         priority = body.options.get('priority', getattr(body_type, 'priority', 0))
         self.app.tasks['celery.chord_unlock'].apply_async(
             (header_result.id, body,), kwargs,


Test patch:
diff --git a/t/unit/backends/test_base.py b/t/unit/backends/test_base.py
index 5d04e8a7d03..9023dc14e57 100644
--- a/t/unit/backends/test_base.py
+++ b/t/unit/backends/test_base.py
@@ -206,7 +206,17 @@ def test_chord_unlock_queue(self, unlock='celery.chord_unlock'):
 
         self.b.apply_chord(header_result_args, body)
         called_kwargs = self.app.tasks[unlock].apply_async.call_args[1]
-        assert called_kwargs['queue'] is None
+        assert called_kwargs['queue'] == 'testcelery'
+
+        routing_queue = Mock()
+        routing_queue.name = "routing_queue"
+        self.app.amqp.router.route = Mock(return_value={
+            "queue": routing_queue
+        })
+        self.b.apply_chord(header_result_args, body)
+        assert self.app.amqp.router.route.call_args[0][1] == body.name
+        called_kwargs = self.app.tasks[unlock].apply_async.call_args[1]
+        assert called_kwargs["queue"] == "routing_queue"
 
         self.b.apply_chord(header_result_args, body.set(queue='test_queue'))
         called_kwargs = self.app.tasks[unlock].apply_async.call_args[1]
@@ -228,7 +238,7 @@ def callback_different_app(result):
             callback_different_app_signature = self.app.signature('callback_different_app')
             self.b.apply_chord(header_result_args, callback_different_app_signature)
             called_kwargs = self.app.tasks[unlock].apply_async.call_args[1]
-            assert called_kwargs['queue'] is None
+            assert called_kwargs['queue'] == 'routing_queue'
 
             callback_different_app_signature.set(queue='test_queue_three')
             self.b.apply_chord(header_result_args, callback_different_app_signature)