Repository: celery/celery

Issue:
Error with default kwargs in __header__ attribute generation
<!--
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].
-->

- [ ] I have read the relevant section in the
  [contribution guide](http://docs.celeryproject.org/en/latest/contributing.html#other-bugs)
  on reporting bugs.
- [ ] 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.
- [ ] 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).
- [ ] 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.
- [ ] 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.
- [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

- None

## Environment & Settings
<!-- Include the contents of celery --version below -->
**Celery version**: 4.3.0
<!-- 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**: 3.7.1
* **Minimal Celery Version**: 4.3.0
* **Minimal Kombu Version**: 4.2.1
* **Minimal Broker Version**: redis==2.10.6
* **Minimal Result Backend Version**: N/A or Unknown
* **Minimal OS and/or Kernel Version**: N/A or Unknown
* **Minimal Broker Client Version**: redis==2.10.6
* **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==2.2.2
appdirs==1.4.3
appnope==0.1.0
argh==0.26.2
attrs==17.4.0
autoflake==1.1
Babel==2.6.0
backports.shutil-get-terminal-size==1.0.0
billiard==3.5.0.3
bleach==3.0.2
boto3==1.7.22
botocore==1.10.22
cachetools==3.1.0
celery==4.3.0
certifi==2018.1.18
chardet==3.0.4
colorama==0.3.9
contextlib2==0.5.5
coverage==4.5.1
decorator==4.2.1
defusedxml==0.5.0
dj-database-url==0.5.0
Django==2.2
django-admin-rangefilter==0.3.12
django-allauth==0.35.0
django-celery-beat==1.1.1
django-cors-middleware==1.3.1
django-cursor-pagination==0.1.2
django-extensions==2.0.0
django-filter==1.1.0
django-formtools==2.1
django-otp==0.5.0
django-phonenumber-field==1.3.0
django-prometheus==1.0.15
django-two-factor-auth==1.8.0
django-viewflow-pro==1.4.2
djangorestframework==3.7.7
djangorestframework-simplejwt==3.2.2
djproxy==2.3.4
docopt==0.6.2
docutils==0.14
elasticsearch==6.0.0
enum34==1.1.6
ephem==3.7.6.0
factory-boy==2.11.1
Faker==0.8.11
flake8==3.5.0
flake8-isort==2.4
flake8-polyfill==1.0.2
freezegun==0.3.11
gevent==1.3.7
google-api-core==1.7.0
google-auth==1.6.2
googleapis-common-protos==1.5.6
graphene==2.0.1
graphene-django==2.0.0
graphql-core==2.0
graphql-relay==0.4.5
greenlet==0.4.15
grpcio==1.17.1
grpcio-tools==1.17.1
gunicorn==19.9.0
idna==2.6
img2pdf==0.3.2
ipdb==0.11
ipython==6.2.1
ipython-genutils==0.2.0
iso8601==0.1.12
isort==4.3.4
jedi==0.11.1
jmespath==0.9.3
jsonfield==2.0.2
kombu==4.2.1
mccabe==0.6.1
mock==2.0.0
mypy==0.641
mypy-extensions==0.4.1
mypy-protobuf==1.7
numpy==1.16.2
oauthlib==2.0.6
opencensus==0.1.10
packaging==17.1
parso==0.1.1
pathlib2==2.3.0
pathtools==0.1.2
pbr==3.1.1
pdfrw==0.4
permissive-search==0.1.7
pexpect==4.4.0
phonenumberslite==8.10.4
pickleshare==0.7.4
Pillow==5.4.1
pkginfo==1.4.2
pluggy==0.6.0
prometheus-client==0.5.0
promise==2.1
prompt-toolkit==1.0.15
protobuf==3.6.1
psycopg2-binary==2.7.6.1
ptyprocess==0.5.2
py==1.5.2
pyasn1==0.4.5
pyasn1-modules==0.2.4
pycodestyle==2.3.1
pycountry==18.5.26
pycurl==7.43.0.1
pyflakes==1.6.0
Pygments==2.2.0
PyJWT==1.6.1
pyparsing==2.2.0
pytest==3.4.1
pytest-cov==2.5.1
pytest-django==3.1.2
pytest-watch==4.1.0
pythia-python==1.5.2
python-dateutil==2.7.0
python-http-client==3.1.0
python3-openid==3.1.0
pytz==2018.3
PyYAML==3.12
qrcode==6.1
raven==6.6.0
readme-renderer==24.0
redis==2.10.6
reportlab==3.5.13
requests==2.20.0
requests_aws4auth==0.9
requests-mock==1.4.0
requests-oauthlib==0.8.0
requests-toolbelt==0.8.0
rsa==4.0
Rx==1.6.1
s3transfer==0.1.13
scandir==1.7
sendgrid==5.3.0
simplegeneric==0.8.1
singledispatch==3.4.0.3
six==1.11.0
snapshottest==0.5.0
termcolor==1.1.0
testfixtures==5.4.0
text-unidecode==1.2
tqdm==4.19.8
traitlets==4.3.2
twine==1.12.1
typed-ast==1.1.0
typing==3.6.4
ulid==1.1
Unidecode==1.0.22
urllib3==1.22
vine==1.1.4
watchdog==0.8.3
wcwidth==0.1.7
webencodings==0.5.1
whitenoise==3.3.1
wrapt==1.10.11
yapf==0.20.2
```

</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
@celery_app.task(name="some_name")
def some_function(
    *,
    first_kw: str = "default value 1",
    second_kw: str,
    third_kw: str,
    n_minus_one_kw: str,
    last_kw: str = "default value 2"
):
    service.make_service(
        kw_1=first_kw,
        kw_2=second_lw,
        kw_3=third_kw,
        kw_4=n_minus_one_kw,
        kw_5=last_kw,
    )

```

</p>
</details>

# Expected Behavior
<!-- Describe in detail what you expect to happen -->
I expect that my function kwargs with default values will be optional. In example I suppose that first_kw and last_kw will be optional, and other will be required keyword arguments. 

# 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.
-->
```
kwonlyargs_optional = [(kw, i) for i, kw in enumerate(spec.kwonlyargs[-split:])]
```
will return (kw, i) tuple for kwonlyargs in reversed order. But if I will pass default value for first and last element, and didn't provide default value for second, third, ... (n-1)th element, then this kwonlyargs_optional will assign optional parameter for (n-1)th element and latest elements, not for first and last. And it will cause an error for typing checking, if you wouldn't provide explicitly kward arg for first kwarg argument.

Possible solution:
```
kwonlyargs_optional = [(kw, i) for i, kw in enumerate(spec.kwonlydefaults.keys())]
``` 



Discussion:
did you find any solution for this?

well, I passed explicitly kwarg's default value and that helped, because I don't want to patch celery. 
so what would be the resolution of this issue in your opinion? you want anyone patch/document or close the issue?
I sent CR and we can solve the issue after merging
I added a test for this in master and marked it as `xfail`ed.
I'll try to come up with a better patch.

Resolving patch:
diff --git a/celery/utils/functional.py b/celery/utils/functional.py
--- a/celery/utils/functional.py
+++ b/celery/utils/functional.py
@@ -259,11 +259,11 @@ def _argsfromspec(spec, replace_defaults=True):
     varargs = spec.varargs
     varkw = spec.varkw
     if spec.kwonlydefaults:
-        split = len(spec.kwonlydefaults)
-        kwonlyargs = spec.kwonlyargs[:-split]
+        kwonlyargs = set(spec.kwonlyargs) - set(spec.kwonlydefaults.keys())
         if replace_defaults:
             kwonlyargs_optional = [
-                (kw, i) for i, kw in enumerate(spec.kwonlyargs[-split:])]
+                (kw, i) for i, kw in enumerate(spec.kwonlydefaults.keys())
+            ]
         else:
             kwonlyargs_optional = list(spec.kwonlydefaults.items())
     else:


Test patch:
diff --git a/t/unit/utils/test_functional.py b/t/unit/utils/test_functional.py
--- a/t/unit/utils/test_functional.py
+++ b/t/unit/utils/test_functional.py
@@ -225,7 +225,6 @@ def f(cls, x):
         fun = head_from_fun(A.f, bound=True)
         assert fun(1) == 1
 
-    @pytest.mark.xfail(reason="Issue #5469")
     def test_kwonly_required_args(self):
         local = {}
         fun = ('def f_kwargs_required(*, a="a", b, c=None):'