Repository: celery/celery

Issue:
Process worker prefork behavior with `app.conf.update(config)`
<!--
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

- [ ] 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.
- [x] I have included the contents of ``pip freeze`` in the issue.
- [x] 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.
- [x] 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

- https://github.com/celery/celery/issues/6307

## 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>

```
software -> celery:5.1.2 (sun-harmonics) kombu:5.1.0 py:3.9.1
            billiard:3.6.4.0 py-amqp:5.0.6
platform -> system:Darwin arch:64bit
            kernel version:20.5.0 imp:CPython
loader   -> celery.loaders.default.Loader
settings -> transport:amqp results:disabled

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>

```
amqp==5.0.6
appdirs==1.4.4
billiard==3.6.4.0
black==20.8b1
celery==5.1.2
click==7.1.2
click-didyoumean==0.0.3
click-plugins==1.1.1
click-repl==0.2.0
flake8==3.9.2
Flask==2.0.1
isort==5.9.1
itsdangerous==2.0.1
Jinja2==3.0.1
kombu==5.1.0
MarkupSafe==2.0.1
mccabe==0.6.1
motor==2.4.0
mypy-extensions==0.4.3
numpy==1.21.0
pathspec==0.8.1
prompt-toolkit==3.0.19
pycodestyle==2.7.0
pyflakes==2.3.1
pymongo==3.11.4
pytz==2021.1
PyYAML==5.4.1
regex==2021.4.4
six==1.16.0
toml==0.10.2
typed-ast==1.4.3
typing-extensions==3.10.0.0
vine==5.0.0
wcwidth==0.2.5
Werkzeug==2.0.1
```

</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>

`celery.py`
```python
from celery import Celery, signals
from click import Option
import codecs
import yaml

def setup(yml_path: str):
    global CONF
    with codecs.open(yml_path, "r", "utf-8") as config_file:
        CONF = yaml.load(config_file, Loader=yaml.FullLoader)

def load_config(yml_path: str):
    conf =setup(yml_path) # Load conf file from custom yaml
    celery_config = conf.get("celery", {})
    app_config = celery_config.get("app", {})

    app.conf.update(app_config)

    return conf
def _create_celery():
    app = Celery(include=["ais.tasks"])
    app.user_options["preload"] = [
        Option(["--config", "-C"], default="config/config.yml")
    ]

    return app

"""
signal handlers
Warning: signal handlers only executed on server side
"""


@signals.user_preload_options.connect
def handle_preload_options(options, **kwargs):
    load_config(options["config"])

app = _create_celery()
```

`config.yml`
```yaml
celery:
  app:
    app_name: parser-worker
    worker_concurrency: 4
    broker_url: redis://localhost:6379/0
```

</p>
</details>

# Expected Behavior
<!-- Describe in detail what you expect to happen -->
Concurrency worker prefork should be 4 process by `app.conf.update` from `config.yml`

# Actual Behavior
<!--
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.
-->
Concurrency worker still prefork 8 process

# Trace Code

## The worker init flow with `click` confused
Module path `.venv/lib/python3.9/site-packages/celery/bin/worker.py`
I found use `click` lib instead of `argparse` in [bin/worker](https://github.com/celery/celery/blob/master/celery/bin/worker.py#L183)
It use `value or ctx.obj.app.conf.worker_concurrency` for lambda value

we hope `ctx.obj.app.conf.worker_concurrency` be any int but `0`.
Unfortunately, it seems not in this case.

`ctx.obj.app.conf.worker_concurrency` was setup after `@handle_preload_options` according to call stack.

The `concurrency` will also be `0` in [worker/worker.py](https://github.com/celery/celery/blob/master/celery/worker/worker.py#L376), though it use `either` func to ` either('worker_concurrency', concurrency)`.
 


Discussion:
Hey @wangha81 :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.

can you work on providing the fix?
Sorry, I don't know which behaviors below is right
- the value at `click` step would set if `worker_concurrency` was given
- `this.concurrency = either('worker_concurrency', concurrency)` would set but `concurrency` if `worker_concurrency` was given

btw, I'm not yet trace the `either` workflow, so I don't know how `either` method works.

Maybe trace in free time but  I have a little busy recently.

Thanks for your response

Resolving patch:
diff --git a/celery/app/defaults.py b/celery/app/defaults.py
--- a/celery/app/defaults.py
+++ b/celery/app/defaults.py
@@ -294,7 +294,7 @@ def __repr__(self):
         cancel_long_running_tasks_on_connection_loss=Option(
             False, type='bool'
         ),
-        concurrency=Option(0, type='int'),
+        concurrency=Option(None, type='int'),
         consumer=Option('celery.worker.consumer:Consumer', type='string'),
         direct=Option(False, type='bool', old={'celery_worker_direct'}),
         disable_rate_limits=Option(


Test patch: