Issue 1:
I am seeing frequent deadlocks when running tasks simplified to the below. (I purged out all the logging and a few database interactions to keep things clear.) Calling the task that calls everything else usually runs <15 tasks before locking, and restarting the workers a few times eventually clears up whatever the problem is (with the remaining tasks running to completion). I realize that the issue is most likely with my code, but would appreciate any advice; I do not see much coverage of class based tasks and wonder if something is wrong there, and do not see any errors or exceptions in my logs. Also, this might be a duplicate of #1352; I am willing to move to Celery 3.1.7 to test, but it will take a bit due to required project restructuring.

Celery worker start:

python app/manage.py celeryd -E --loglevel=INFO -Q db_upload,default,api_call,management,rr -c 1

Versioning:

celery==3.0.19
celery-with-redis==3.0
django-celery==3.0.17
kombu==2.5.10
billiard==2.7.3.28

Celery config:

import djcelery
djcelery.setup_loader()
BROKER_URL = getenv('CLOUDAMQP_URL')
CELERY_RESULT_BACKEND = getenv('REDISTOGO_URL')

BROKER_POOL_LIMIT = int(getenv('BROKER_POOL_LIMIT', 1)) #1
BROKER_CONNECTION_TIMEOUT = int(getenv('BROKER_CONNECTION_TIMEOUT')) #6
CELERYD_CONCURRENCY = int(getenv('CELERYD_CONCURRENCY')) #1
CELERY_TASK_RESULT_EXPIRES = int(getenv('RESULT_EXPIRY_RATE')) 600
CELERY_IGNORE_RESULT = getenv('CELERY_IGNORE_RESULT') == 'True' #False
CELERYD_TASK_TIME_LIMIT = int(getenv('CELERYD_TASK_TIME_LIMIT')) #600
CELERY_REDIS_MAX_CONNECTIONS = int(getenv('CELERY_REDIS_MAX_CONNECTIONS')) #40

CELERY_IMPORTS = ("app.management.tasks.api_calls",)
BROKER_CONNECTION_RETRY = True
CELERY_STORE_ERRORS_EVEN_IF_IGNORED = True
CELERY_ACKS_LATE = True
CELERYD_TASK_SOFT_TIME_LIMIT = 59
CELERY_SEND_TASK_ERROR_EMAILS = True

Tasks:

class BaseTask(Task):

abstract=True
def __call__(self, *args, **kwargs):
#logger.info("Starting to run")
self.api_context = kwargs['api_context']
del kwargs['api_context']
return super(BaseTask, self).__call__(*args, **kwargs)

class ApiFollower(Task):

abstract=True
def __call__(self, *args, **kwargs):
self.result = args[0].get('result',{})
self.api_context = args[0].get('api_context',{})
return super(ApiFollower, self).__call__(*args, **kwargs)

class RefreshRecords(BaseTask):

def run(self):
check_list = get_users()
for counter, user in enumerate(check_list, start = 1):
context = ApiContext()
context.account_id=user.id

if self.api_context.records_requested is None:
context.records_requested = 20
else:
context.records_requested = self.api_context.records_requested

if self.api_context.records_desired is None:
context.records_desired = 20
else:
context.records_desired = self.api_context.records_desired

context.deepcopy=True
context.start_scrape_time=now()
context.last_scrape_time=user.last_scrape_time
ac = ApiCall()
rr = RetrieveRecords()
chain(vac.s(mode='<mode>',api_context=context),rr.s()).delay()
tasks.register(RefreshRecords)

class ApiCall(BaseTask):
def run(self, mode, **kwargs):
self.api_context.key = API_KEY
modeDict = {<name: url several times>}
try:
url = modeDict[mode]
except KeyError:
logger.info("Keyerrors!")

URL = url + '?' + urlencode(self.api_context.toUrlDict(mode))

# Exception handling for the URL opening.
try:
pageaccess = urllib2.urlopen(URL, timeout=5)
except urllib2.HTTPError, err:
if err.code in [104, 111, 401, 403, 404, 500, 503]:
self.retry(mode=mode)
else:
self.retry(mode=mode)
except (BadStatusLine, urllib2.URLError, ssl.SSLError, socket.timeout) as err:
self.retry(mode=mode)

data = json.loads(pageaccess.read())
data['api_context'] = self.api_context
return data
tasks.register(ApiCall)

class RetrieveRecords(ApiFollower):
"""This is tricky. The API lets you take slices of data, but you only know the indices to use in the call from the previously taken slices. Further, to get actual information for the records in a slice, you need another API call. Here we see if the previous call worked, spawn the detail calls as needed, and either hit the API again or finish up, depending on whether we wanted any more records."""
def run(self, urldata):
try:
if self.result['status'] == 1:
self.spawnDetailCalls()
if self.moreResultsLeft():
self.rebound()
#Successful closeout
else:
logger.info("Cleaning up")
self.cleanup()
return True
else:
logger.error("Unhandled status: "+str(self.result['status']))
return True
except Exception, err:
logger.error("ERROR!:{0}".format(err))
return False

def rebound(self):
self.api_context.start_at_record_id = self.result['information'][-1]['id']
ac = ApiCall()
rr = RetrieveRecords()
pass_context = deepcopy(self.api_context)
chain(ac.s(mode='<mode>',api_context=pass_context), rr.s()).delay()

def cleanup(self):
<do stuff>

def spawnDetailCalls(self):
for result in self.result['information']:
ac = ApiCall()
ud = UploadData()
self.api_context.record_id=result['record_id']
self.api_context.processed+=1
pass_context = deepcopy(self.api_context)
chain(ac.s(mode='<mode>',api_context=pass_context), ud.s()).delay()

def moreResultsLeft(self):
if self.result['results_remaining'] == 0:
return False
elif self.api_context.processed >= self.api_context.records_desired:
return False
else:
if self.api_context.deepcopy is False:
return self.api_context.last_scrape_time < self.result['information'][-1]['start_time']
else:
return True
tasks.register(RetrieveRecords)

Issue 2:
Checklist

I have verified that the issue exists against the master branch of Celery.

This has already been asked to the discussion group first.

I have read the relevant section in the

contribution guide

on reporting bugs.

I have checked the issues list

for similar or identical bug reports.

I have checked the pull requests list

for existing proposed fixes.

I have checked the commit log

to find out if the bug was already fixed in the master branch.

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

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

Related Issues

None

Possible Duplicates

None

Environment & Settings

Celery version:

5.1.0 (sun-harmonics)

celery report Output:

Steps to Reproduce

In [1]: from celery.utils.functional import regen
In [2]: from collections import deque
In [3]: l = regen(deque([1]))
In [4]: l
Out[4]: [1]
In [5]: l
Out[5]: [1, 1]
In [6]: l
Out[6]: [1, 1, 1]

When using .map() with non-list, non-tuple sequence passed all the items are processed 3 times:

@shared_task
def print_task(i):
print(i)

# Print out 42 three times, can also use Django Queryset or any other Sequence
print_task.map(deque([42])).delay()

Required Dependencies

No dependencies

Minimal Python Version: checked 3.8.2 and 3.9.0+

Minimal Celery Version: checked 4.4.2, 4.4.7 and 5.10

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

pip freeze Output:

amqp==5.0.6
backcall==0.2.0
billiard==3.6.4.0
-e git+git@github.com:celery/celery.git@025bad6e93087414b3ddc288060c367d1937774b#egg=celery
click==7.1.2
click-didyoumean==0.0.3
click-plugins==1.1.1
click-repl==0.1.6
decorator==5.0.9
ipython==7.23.1
ipython-genutils==0.2.0
jedi==0.18.0
kombu==5.1.0
matplotlib-inline==0.1.2
parso==0.8.2
pexpect==4.8.0
pickleshare==0.7.5
prompt-toolkit==3.0.18
ptyprocess==0.7.0
Pygments==2.9.0
pytz==2021.1
six==1.16.0
traitlets==5.0.5
vine==5.0.0
wcwidth==0.2.5

Other Dependencies

N/A

Minimally Reproducible Test Case

In [1]: from celery.utils.functional import regen
In [2]: from collections import deque
In [3]: l = regen(deque([1]))
In [4]: l
Out[4]: [1]
In [5]: l
Out[5]: [1, 1]
In [6]: l
Out[6]: [1, 1, 1]

Expected Behavior

Expected for regen() to not duplicate entires and for .map() to run each item once.

Actual Behavior

See above.