-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
fix SNS FIFO ordering #12285
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
fix SNS FIFO ordering #12285
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
555d81a
implement topic partitioned executor
bentsku a018531
add test
bentsku 34becd5
add return statement to exit the worker
bentsku cc73548
fix signature and explicitly pass the `topic` to the submit call
bentsku aa58bcb
Avoid `continue` flow in the worker thread
bentsku a50cbfe
update assertion
bentsku 2550f06
address PR comments
bentsku File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
import itertools | ||
import logging | ||
import os | ||
import queue | ||
import threading | ||
|
||
LOG = logging.getLogger(__name__) | ||
|
||
|
||
def _worker(work_queue: queue.Queue): | ||
try: | ||
while True: | ||
work_item = work_queue.get(block=True) | ||
if work_item is None: | ||
return | ||
work_item.run() | ||
# delete reference to the work item to avoid it being in memory until the next blocking `queue.get` call returns | ||
del work_item | ||
|
||
except Exception: | ||
LOG.exception("Exception in worker") | ||
|
||
|
||
class _WorkItem: | ||
def __init__(self, fn, args, kwargs): | ||
self.fn = fn | ||
self.args = args | ||
self.kwargs = kwargs | ||
|
||
def run(self): | ||
try: | ||
self.fn(*self.args, **self.kwargs) | ||
except Exception: | ||
LOG.exception("Unhandled Exception in while running %s", self.fn.__name__) | ||
|
||
|
||
class TopicPartitionedThreadPoolExecutor: | ||
""" | ||
This topic partition the work between workers based on Topics. | ||
It guarantees that each Topic only has one worker assigned, and thus that the tasks will be executed sequentially. | ||
|
||
Loosely based on ThreadPoolExecutor for stdlib, but does not return Future as SNS does not need it (fire&forget) | ||
Could be extended if needed to fit other needs. | ||
|
||
Currently, we do not re-balance between workers if some of them have more load. This could be investigated. | ||
""" | ||
|
||
# Used to assign unique thread names when thread_name_prefix is not supplied. | ||
_counter = itertools.count().__next__ | ||
|
||
def __init__(self, max_workers: int = None, thread_name_prefix: str = ""): | ||
if max_workers is None: | ||
max_workers = min(32, (os.cpu_count() or 1) + 4) | ||
if max_workers <= 0: | ||
raise ValueError("max_workers must be greater than 0") | ||
|
||
self._max_workers = max_workers | ||
self._thread_name_prefix = ( | ||
thread_name_prefix or f"TopicThreadPoolExecutor-{self._counter()}" | ||
) | ||
|
||
# for now, the pool isn't fair and is not redistributed depending on load | ||
self._pool = {} | ||
self._shutdown = False | ||
self._lock = threading.Lock() | ||
self._threads = set() | ||
self._work_queues = [] | ||
self._cycle = itertools.cycle(range(max_workers)) | ||
|
||
def _add_worker(self): | ||
work_queue = queue.SimpleQueue() | ||
self._work_queues.append(work_queue) | ||
thread_name = f"{self._thread_name_prefix}_{len(self._threads)}" | ||
t = threading.Thread(name=thread_name, target=_worker, args=(work_queue,)) | ||
t.daemon = True | ||
t.start() | ||
self._threads.add(t) | ||
|
||
def _get_work_queue(self, topic: str) -> queue.SimpleQueue: | ||
if not (work_queue := self._pool.get(topic)): | ||
if len(self._threads) < self._max_workers: | ||
self._add_worker() | ||
|
||
# we cycle through the possible indexes for a work queue, in order to distribute the load across | ||
# once we get to the max amount of worker, the cycle will start back at 0 | ||
index = next(self._cycle) | ||
work_queue = self._work_queues[index] | ||
|
||
# TODO: the pool is not cleaned up at the moment, think about the clean-up interface | ||
self._pool[topic] = work_queue | ||
return work_queue | ||
|
||
def submit(self, fn, topic, /, *args, **kwargs) -> None: | ||
with self._lock: | ||
work_queue = self._get_work_queue(topic) | ||
|
||
if self._shutdown: | ||
raise RuntimeError("cannot schedule new futures after shutdown") | ||
|
||
w = _WorkItem(fn, args, kwargs) | ||
work_queue.put(w) | ||
|
||
def shutdown(self, wait=True): | ||
with self._lock: | ||
self._shutdown = True | ||
|
||
# Send a wake-up to prevent threads calling | ||
# _work_queue.get(block=True) from permanently blocking. | ||
for work_queue in self._work_queues: | ||
work_queue.put(None) | ||
|
||
if wait: | ||
for t in self._threads: | ||
t.join() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
empty snapshot is because we're using a transformer fixture with
autouse
, so it creates an entry even if no snapshot are recorded 😅