-
-
Notifications
You must be signed in to change notification settings - Fork 33.2k
gh-124694: Add concurrent.futures.InterpreterPoolExecutor #124548
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
ericsnowcurrently
merged 39 commits into
python:main
from
ericsnowcurrently:interpreter-pool-executor
Oct 16, 2024
Merged
Changes from 10 commits
Commits
Show all changes
39 commits
Select commit
Hold shift + click to select a range
5c69d38
Make ThreadPoolExecutor extensible.
ericsnowcurrently 01789be
Add InterpreterPoolExecutor.
ericsnowcurrently 6def4be
Clean up the interpreter if initialize() fails.
ericsnowcurrently 84993a5
Add a missing import.
ericsnowcurrently c540cf0
Fix some typos.
ericsnowcurrently 45d584d
Add more tests.
ericsnowcurrently c90c016
Add docs.
ericsnowcurrently 1cb4657
Add a NEwS entry.
ericsnowcurrently 4dc0989
Fix the last test.
ericsnowcurrently 57b2db6
Add more tests.
ericsnowcurrently 75e11d2
Simplify ExecutionFailed.
ericsnowcurrently 69c2b8e
Fix the signature of resolve_task().
ericsnowcurrently f03c314
Capture any uncaught exception.
ericsnowcurrently 4806d9f
Add TODO comments.
ericsnowcurrently efc0395
Docs fixes.
ericsnowcurrently a29aee3
Automatically apply textwrap.dedent() to scripts.
ericsnowcurrently 8bab457
Fix the WASI build.
ericsnowcurrently cd29914
wasi
ericsnowcurrently 0287f3b
Ignore race in test.
ericsnowcurrently 80cd7b1
Add BrokenInterpreterPool.
ericsnowcurrently f8d4273
Tweak the docs.
ericsnowcurrently 3a8bfce
Clarify the InterpreterPoolExecutor docs.
ericsnowcurrently af6c27a
Catch all exceptions.
ericsnowcurrently 8c0a405
Factor out exception serialization helpers.
ericsnowcurrently 1ae7ca2
Set the ExecutionFailed error as __cause__.
ericsnowcurrently d24e85d
Drop the exception serialization helpers.
ericsnowcurrently 05a03ad
Always finalize if there is an error in initialize().
ericsnowcurrently f150931
Explicitly note the problem with functions defined in __main__.
ericsnowcurrently 97d0292
Handle the case where interpreters.queues doesn't exist.
ericsnowcurrently baf0504
Merge branch 'main' into interpreter-pool-executor
ericsnowcurrently 5c3a327
Add a What's New entry about InterpreterPoolExecutor.
ericsnowcurrently a2032a8
Fix a typo.
ericsnowcurrently 54119b8
Fix the documented signature.
ericsnowcurrently 744dca7
Test and document asyncio support.
ericsnowcurrently f61d62d
Apply suggestions from code review
ericsnowcurrently ee65bb2
Expand the docs.
ericsnowcurrently a7f5c50
For now, drop support for scripts.
ericsnowcurrently b148e09
Fix a TODO comment.
ericsnowcurrently e365ae7
Fix the docs.
ericsnowcurrently 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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,188 @@ | ||
"""Implements InterpreterPoolExecutor.""" | ||
|
||
import pickle | ||
from . import thread as _thread | ||
import _interpreters | ||
import _interpqueues | ||
|
||
|
||
LINESEP = ''' | ||
''' | ||
ZeroIntensity marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
|
||
_EXEC_FAILURE_STR = """ | ||
{superstr} | ||
Uncaught in the interpreter: | ||
{formatted} | ||
""".strip() | ||
|
||
|
||
class ExecutionFailed(_interpreters.InterpreterError): | ||
"""An unhandled exception happened during execution.""" | ||
|
||
def __init__(self, excinfo): | ||
msg = excinfo.formatted | ||
if not msg: | ||
if excinfo.type and excinfo.msg: | ||
msg = f'{excinfo.type.__name__}: {excinfo.msg}' | ||
else: | ||
msg = excinfo.type.__name__ or excinfo.msg | ||
super().__init__(msg) | ||
self.excinfo = excinfo | ||
|
||
def __str__(self): | ||
try: | ||
formatted = self.excinfo.errdisplay | ||
except Exception: | ||
return super().__str__() | ||
else: | ||
return _EXEC_FAILURE_STR.format( | ||
superstr=super().__str__(), | ||
formatted=formatted, | ||
) | ||
|
||
|
||
UNBOUND = 2 # error; this should not happen. | ||
|
||
|
||
class WorkerContext(_thread.WorkerContext): | ||
|
||
@classmethod | ||
def prepare(cls, initializer, initargs, shared): | ||
if isinstance(initializer, str): | ||
if initargs: | ||
raise ValueError(f'an initializer script does not take args, got {initargs!r}') | ||
initscript = initializer | ||
# Make sure the script compiles. | ||
# XXX Keep the compiled code object? | ||
compile(initscript, '<string>', 'exec') | ||
elif initializer is not None: | ||
pickled = pickle.dumps((initializer, initargs)) | ||
initscript = f'''if True: | ||
import pickle | ||
initializer, initargs = pickle.loads({pickled!r}) | ||
initializer(*initargs) | ||
''' | ||
else: | ||
initscript = None | ||
def create_context(): | ||
return cls(initscript, shared) | ||
def resolve_task(cls, fn, args, kwargs): | ||
if isinstance(fn, str): | ||
if args or kwargs: | ||
raise ValueError(f'a script does not take args or kwargs, got {args!r} and {kwargs!r}') | ||
data = fn | ||
kind = 'script' | ||
else: | ||
data = pickle.dumps((fn, args, kwargs)) | ||
kind = 'function' | ||
return (data, kind) | ||
return create_context, resolve_task | ||
|
||
@classmethod | ||
def _run_pickled_func(cls, data, resultsid): | ||
fn, args, kwargs = pickle.loads(data) | ||
res = fn(*args, **kwargs) | ||
# Send the result back. | ||
try: | ||
_interpqueues.put(resultsid, res, 0, UNBOUND) | ||
except _interpreters.NotShareableError: | ||
res = pickle.dumps(res) | ||
_interpqueues.put(resultsid, res, 1, UNBOUND) | ||
|
||
def __init__(self, initscript, shared=None): | ||
self.initscript = initscript or '' | ||
self.shared = dict(shared) if shared else None | ||
self.interpid = None | ||
self.resultsid = None | ||
|
||
def __del__(self): | ||
if self.interpid is not None: | ||
self.finalize() | ||
|
||
def _exec(self, script): | ||
assert self.interpid is not None | ||
excinfo = _interpreters.exec(self.interpid, script, restrict=True) | ||
if excinfo is not None: | ||
raise ExecutionFailed(excinfo) | ||
|
||
def initialize(self): | ||
assert self.interpid is None, self.interpid | ||
self.interpid = _interpreters.create(reqrefs=True) | ||
try: | ||
_interpreters.incref(self.interpid) | ||
|
||
initscript = f"""if True: | ||
from {__name__} import WorkerContext | ||
""" | ||
initscript += LINESEP + self.initscript | ||
self._exec(initscript) | ||
|
||
if self.shared: | ||
_interpreters.set___main___attrs( | ||
self.interpid, self.shared, restrict=True) | ||
|
||
maxsize = 0 | ||
fmt = 0 | ||
self.resultsid = _interpqueues.create(maxsize, fmt, UNBOUND) | ||
except _interpreters.InterpreterNotFoundError: | ||
raise # re-raise | ||
except BaseException: | ||
self.finalize() | ||
raise # re-raise | ||
|
||
def finalize(self): | ||
interpid = self.interpid | ||
resultsid = self.resultsid | ||
self.resultsid = None | ||
self.interpid = None | ||
if resultsid is not None: | ||
try: | ||
_interpqueues.destroy(resultsid) | ||
except _interpqueues.QueueNotFoundError: | ||
pass | ||
if interpid is not None: | ||
try: | ||
_interpreters.decref(interpid) | ||
except _interpreters.InterpreterNotFoundError: | ||
pass | ||
|
||
def run(self, task): | ||
data, kind = task | ||
if kind == 'script': | ||
self._exec(data) | ||
return None | ||
elif kind == 'function': | ||
self._exec( | ||
f'WorkerContext._run_pickled_func({data!r}, {self.resultsid})') | ||
obj, pickled, unboundop = _interpqueues.get(self.resultsid) | ||
assert unboundop is None, unboundop | ||
return pickle.loads(obj) if pickled else obj | ||
else: | ||
raise NotImplementedError(kind) | ||
|
||
|
||
class InterpreterPoolExecutor(_thread.ThreadPoolExecutor): | ||
|
||
@classmethod | ||
def prepare_context(cls, initializer, initargs, shared): | ||
return WorkerContext.prepare(initializer, initargs, shared) | ||
|
||
def __init__(self, max_workers=None, thread_name_prefix='', | ||
initializer=None, initargs=(), shared=None): | ||
"""Initializes a new InterpreterPoolExecutor instance. | ||
Args: | ||
max_workers: The maximum number of interpreters that can be used to | ||
execute the given calls. | ||
thread_name_prefix: An optional name prefix to give our threads. | ||
initializer: A callable or script used to initialize | ||
each worker interpreter. | ||
initargs: A tuple of arguments to pass to the initializer. | ||
shared: A mapping of shareabled objects to be inserted into | ||
each worker interpreter. | ||
""" | ||
super().__init__(max_workers, thread_name_prefix, | ||
initializer, initargs, shared=shared) |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.