Skip to content

Commit 1a4ddea

Browse files
authored
fix: Remove stdlib multiprocessing with pathos (#47)
* fix: pathos.ProcessPool uses multiprocess * fix: can't pickle mp.Queue -> mp.Manager().Queue() * refactor: switch from default start method to targeted spawn context * refactor: drop mp.Queue() for error handling * fix: skip caught StopIteration *instances*
1 parent 2a8e3c1 commit 1a4ddea

3 files changed

Lines changed: 29 additions & 23 deletions

File tree

‎requirements_dev.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
moto[all]
1+
moto[all,server]
22
pytest

‎taskqueue/taskqueue.py‎

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import sys
1515

1616
import gevent.pool
17-
import multiprocessing as mp
17+
import multiprocess as mp # used by pathos.pools.ProcessPool
1818
import numpy as np
1919
import pathos.pools
2020
from tqdm import tqdm
@@ -472,15 +472,15 @@ def execute(self, progress=True, parallel=None, total=None):
472472

473473
# Don't fork, spawn entirely new processes. This
474474
# avoids accidental deadlocks.
475-
mp.set_start_method("spawn", force=True)
475+
spawn_ctx = mp.get_context("spawn")
476476

477477
with tqdm(total=total, desc="Tasks", disable=(not progress)) as pbar:
478478
if self.parallel == 1:
479479
while self.queue:
480480
_task_execute(self.queue.pop(0))
481481
pbar.update()
482482
else:
483-
with pathos.pools.ProcessPool(self.parallel) as executor:
483+
with pathos.pools.ProcessPool(self.parallel, context=spawn_ctx) as executor:
484484
for _ in executor.imap(_task_execute, self.queue):
485485
pbar.update()
486486

@@ -513,8 +513,6 @@ def soloprocess_upload(QueueClass, queue_name, tasks):
513513
tq = QueueClass(queue_name, progress=False)
514514
return tq.insert(tasks, skip_insert_counter=True)
515515

516-
error_queue = mp.Queue()
517-
518516
def multiprocess_upload(QueueClass, queue_name, tasks, parallel=True, total=None):
519517
if parallel is True:
520518
parallel = mp.cpu_count()
@@ -526,11 +524,10 @@ def multiprocess_upload(QueueClass, queue_name, tasks, parallel=True, total=None
526524

527525
def capturing_soloprocess_upload(*args, **kwargs):
528526
try:
529-
return soloprocess_upload(*args, **kwargs)
527+
return (soloprocess_upload(*args, **kwargs), None)
530528
except Exception as err:
531529
print(err)
532-
error_queue.put(err)
533-
return 0
530+
return (0, err)
534531

535532
uploadfn = partial(
536533
capturing_soloprocess_upload, QueueClass, queue_name
@@ -569,12 +566,17 @@ def capturing_soloprocess_upload(*args, **kwargs):
569566

570567
# Don't fork, spawn entirely new processes. This
571568
# avoids accidental deadlocks.
572-
mp.set_start_method("spawn", force=True)
569+
spawn_ctx = mp.get_context("spawn")
573570

574571
ct = 0
572+
errors = []
575573
with tqdm(desc="Upload", total=total) as pbar:
576-
with pathos.pools.ProcessPool(parallel) as pool:
577-
for num_inserted in pool.imap(uploadfn, sip(tasks, block_size)):
574+
with pathos.pools.ProcessPool(parallel, context=spawn_ctx) as pool:
575+
for num_inserted, err in pool.imap(uploadfn, sip(tasks, block_size)):
576+
if err is not None:
577+
if not isinstance(err, StopIteration):
578+
errors.append(err)
579+
continue
578580
pbar.update(num_inserted)
579581
ct += num_inserted
580582

@@ -584,14 +586,8 @@ def capturing_soloprocess_upload(*args, **kwargs):
584586
os.environ["no_proxy"] = no_proxy
585587
# task.__class__.__module__ = cls_module
586588

587-
if not error_queue.empty():
588-
errors = []
589-
while not error_queue.empty():
590-
err = error_queue.get()
591-
if err is not StopIteration:
592-
errors.append(err)
593-
if len(errors):
594-
raise Exception(errors)
589+
if errors:
590+
raise Exception(errors)
595591

596592
return ct
597593

‎test/test_taskqueue.py‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import time
55

66
from moto import mock_aws
7-
87
from six.moves import range
98
import pytest
109

@@ -18,7 +17,7 @@
1817
from taskqueue.queueables import totask
1918
from taskqueue.queueablefns import tofunc, UnregisteredFunctionError, func2task
2019

21-
@pytest.fixture(scope='function')
20+
@pytest.fixture(scope='session')
2221
def aws_credentials():
2322
"""Mocked AWS Credentials for moto."""
2423
os.environ['AWS_ACCESS_KEY_ID'] = 'testing'
@@ -35,6 +34,17 @@ def sqs(aws_credentials):
3534
client.create_queue(QueueName='test-pull-queue')
3635
yield client
3736

37+
@pytest.fixture(scope='session')
38+
def sqs_server(aws_credentials):
39+
from moto.server import ThreadedMotoServer
40+
server = ThreadedMotoServer(port=0)
41+
server.start()
42+
host, port = server.get_host_and_port()
43+
os.environ['AWS_ENDPOINT_URL'] = f"http://{host}:{port}"
44+
yield
45+
del os.environ['AWS_ENDPOINT_URL']
46+
server.stop()
47+
3848
QURLS = {
3949
'sqs': 'test-pull-queue',
4050
'fq': '/tmp/removeme/taskqueue/fq',
@@ -269,7 +279,7 @@ def test_local_taskqueue():
269279
assert tq.insert(epts) == 200
270280

271281
@pytest.mark.parametrize('protocol', PROTOCOL)
272-
def test_parallel_insert_all(sqs, protocol):
282+
def test_parallel_insert_all(sqs, sqs_server, protocol):
273283
import pathos_issue
274284

275285
path = getpath(protocol)

0 commit comments

Comments
 (0)