Repository: celery/celery

Issue:
Jobs in AsynPool remain in cache forever if the connection is dropped
<!--
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.
- [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.
- [ ] 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**: 5.1.2
<!-- 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.0
            billiard:3.6.4.0 py-amqp:5.0.6
platform -> system:Linux arch:64bit, ELF
            kernel version:5.11.0-22-generic imp:CPython
loader   -> celery.loaders.app.AppLoader
settings -> transport:amqp results:disabled

broker_url: 'amqp://guest:********@localhost:5672//'
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**: 1.x
* **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>

```
aiohttp==3.7.4.post0
alabaster==0.7.12
amqp==5.0.6
appdirs==1.4.4
async-timeout==3.0.1
attrs==20.3.0
autoflake==1.4
autopep8==1.5.7
aws-xray-sdk==0.95
azure-common==1.1.5
azure-nspkg==3.0.2
azure-storage==0.36.0
azure-storage-common==1.1.0
azure-storage-nspkg==3.1.0
Babel==2.8.0
backcall==0.2.0
billiard==3.6.4.0
bleach==3.2.1
boto==2.49.0
boto3==1.16.9
botocore==1.19.9
bump2version==1.0.1
bumpversion==0.6.0
case==1.5.3
cassandra-driver==3.20.2
-e git+git@github.com:celery/celery.git@7b5a44d646f43288fb546da10a1141347b01543b#egg=celery
Cerberus==1.3.2
certifi==2020.12.5
cffi==1.14.5
cfgv==3.2.0
chardet==4.0.0
click==7.1.2
click-didyoumean==0.0.3
click-plugins==1.1.1
click-repl==0.1.6
codecov==2.1.11
colorama==0.4.4
couchbase==3.1.3
coverage==5.4
cryptography==3.4.6
DateTime==4.3
decorator==4.4.2
deepmerge==0.1.1
dephell-archive==0.1.7
dephell-argparse==0.1.3
dephell-changelogs==0.0.1
dephell-discover==0.2.10
dephell-licenses==0.1.7
dephell-links==0.1.5
dephell-markers==1.0.3
dephell-pythons==0.1.15
dephell-setuptools==0.2.4
dephell-shells==0.1.5
dephell-specifier==0.2.2
dephell-venvs==0.1.18
dephell-versioning==0.1.2
diff-cover==4.2.3
distlib==0.3.1
dnspython==1.16.0
docker==4.3.1
docutils==0.16
durationpy==0.5
ecdsa==0.16.0
elasticsearch==7.9.1
ephem==3.7.7.1
eventlet==0.29.1
filelock==3.0.12
flower==0.9.5
future==0.18.2
gevent==21.1.2
greenlet==0.4.17
humanize==3.1.0
identify==1.5.6
idna==2.10
imagesize==1.2.0
importlib-metadata==4.0.1
inflect==3.0.2
iniconfig==1.1.1
ipython==7.19.0
ipython-genutils==0.2.0
isort==5.9.1
jedi==0.17.2
jeepney==0.6.0
Jinja2==2.11.2
jinja2-pluralize==0.3.0
jmespath==0.10.0
jsondiff==1.1.1
jsonpickle==1.4.1
keyring==21.5.0
kombu==5.1.0
linecache2==1.0.0
m2r==0.2.1
MarkupSafe==1.1.1
mistune==0.8.4
mock==4.0.2
moto==1.3.7
msgpack==1.0.0
multidict==5.1.0
mypy-extensions==0.4.3
nodeenv==1.5.0
nose==1.3.7
packaging==20.9
parso==0.7.1
pbr==5.5.1
pexpect==4.8.0
pickleshare==0.7.5
pkginfo==1.6.1
pluggy==0.13.1
pre-commit==2.8.2
prometheus-client==0.8.0
prompt-toolkit @ file:///home/thedrow/.cache/pypoetry/artifacts/85/ed/40/229a34dee2081fd935c85f600bfcddb0974a96a88f099412c62b58d4fa/prompt_toolkit-3.0.3-py3-none-any.whl
ptyprocess==0.6.0
py==1.10.0
pyaml==20.4.0
pyArango==1.3.4
pycodestyle==2.7.0
pycouchdb==1.14.1
pycparser==2.20
pycryptodome==3.9.8
pycurl==7.43.0.5
pydocumentdb==2.3.2
pyflakes==2.2.0
Pygments==2.7.3
pylibmc==1.6.1
pymongo==3.11.0
pyparsing==2.4.7
pyrsistent==0.17.3
pytest==6.2.2
pytest-celery==0.0.0a1
pytest-cov==2.11.1
pytest-rerunfailures==9.1.1
pytest-subtests==0.3.2
pytest-timeout==1.4.2
pytest-travis-fold==1.3.0
python-consul==1.1.0
python-dateutil==2.8.1
python-jose==2.0.2
python-memcached==1.59
pytz @ file:///home/thedrow/.cache/pypoetry/artifacts/b0/a7/8d/54de3ab4d1ff29abbbca1e9ccbaefdc2a1b290138311b84f73bee16de1/pytz-2021.1-py2.py3-none-any.whl
pyupgrade==2.19.1
pyupgrade-directories==0.2.0
PyYAML==5.3.1
readme-renderer==28.0
redis==3.5.3
requests==2.25.1
requests-toolbelt==0.9.1
responses==0.12.0
rfc3986==1.4.0
ruamel.yaml==0.16.13
ruamel.yaml.clib==0.2.2
s3transfer==0.3.3
SecretStorage==3.3.0
shellingham==1.4.0
simplejson==3.17.2
six==1.15.0
snowballstemmer==2.0.0
softlayer-messaging==1.0.3
Sphinx==3.3.0
sphinx-celery==2.0.0
sphinx-click==2.5.0
sphinx-testing==0.7.2
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==1.0.3
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.4
SQLAlchemy==1.3.23
tblib==1.7.0
tokenize-rt==4.1.0
toml==0.10.2
toml-sort==0.18.0
tomlkit==0.7.0
tornado==6.1
tqdm==4.54.1
traceback2==1.4.0
traitlets==5.0.5
twine==3.4.1
typing-extensions==3.7.4.3
unittest2==1.1.0
urllib3==1.26.3
vine==5.0.0
virtualenv==20.1.0
wcwidth==0.2.5
webencodings==0.5.1
websocket-client==0.57.0
Werkzeug==1.0.1
wrapt==1.12.1
xmltodict==0.12.0
yarl==1.6.3
yaspin==1.4.1
zipp==3.4.0
zope.event==4.5.0
zope.interface==5.1.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.
-->
To reproduce the issue you must force close the connection and cause AsynPool to be flushed.
Missing a heartbeat due to a breakpoint does the trick.
See https://github.com/celery/celery/blob/681e72edb918c8ff315665a6abbfc6dd99f303e2/celery/concurrency/asynpool.py#L978-L1038

<details>
<p>

```python
# Sending any task would do
some_task.delay()
```

</p>
</details>

# Expected Behavior
<!-- Describe in detail what you expect to happen -->
The pool's job cache should be completely empty after we flush it.

# 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.
-->

Canceled jobs remain in the cache and are never cleaned up since the pool doesn't use the worker's synack capability (not sure what that is, actually).
This is a problem since we keep the job's payload (which may be arbitrarily large) forever.
Given enough uptime, whenever there are enough connection drops, we accumulate new jobs that are never garbage collected.

This has been the case from the moment AsynPool has been written, so it seems.



Discussion:

Resolving patch:
diff --git a/celery/concurrency/asynpool.py b/celery/concurrency/asynpool.py
--- a/celery/concurrency/asynpool.py
+++ b/celery/concurrency/asynpool.py
@@ -978,10 +978,14 @@ def _write_ack(fd, ack, callback=None):
     def flush(self):
         if self._state == TERMINATE:
             return
-        # cancel all tasks that haven't been accepted so that NACK is sent.
-        for job in self._cache.values():
+        # cancel all tasks that haven't been accepted so that NACK is sent
+        # if synack is enabled.
+        for job in tuple(self._cache.values()):
             if not job._accepted:
-                job._cancel()
+                if self.synack:
+                    job._cancel()
+                else:
+                    job.discard()
 
         # clear the outgoing buffer as the tasks will be redelivered by
         # the broker anyway.


Test patch: