# Buggy code
def cache_distribution(cls, zf, source, target_dir):
    # type: (ZipFile, str, str) -> Distribution
    """Possibly cache a wheel from within a zipfile into `target_dir`.

    Given a zipfile handle and a source path prefix corresponding to a wheel install embedded within
    that zip, maybe extract the wheel install into the target cache and then return a distribution
    from the cache.

    :param zf: An open zip file (a zipped pex).
    :param source: The path prefix of a wheel install embedded in the zip file.
    :param target_dir: The directory to cache the distribution in if not already cached.
    :returns: The cached distribution.
    """
    with atomic_directory(target_dir, source=source) as target_dir_tmp:
        if target_dir_tmp is None:
            TRACER.log("Using cached {}".format(target_dir))
        else:
            with TRACER.timed(
                "Caching {}:{} in {}".format(zf.filename, source, target_dir)
            ):
                for name in zf.namelist():
                    if name.startswith(source) and not name.endswith("/"):
                        zf.extract(name, target_dir_tmp)

    dist = DistributionHelper.distribution_from_path(target_dir)
    assert dist is not None, "Failed to cache distribution: {} ".format(source)
    return dist


# Traceback (pants.engine.internals.scheduler.ExecutionError)
23:06:05.36 [INFO] Starting: Resolving 3rdparty/python/constraints.txt
23:06:05.38 [WARN] /home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/base/exception_sink.py:313: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats
process_title=setproctitle.getproctitle(),
23:06:05.38 [ERROR] 1 Exception encountered:
Engine traceback:
in select
in `typecheck` goal
in Typecheck using MyPy
in pants.backend.python.typecheck.mypy.rules.mypy_typecheck_partition
in pants.backend.python.util_rules.pex.create_pex
in pants.engine.process.fallible_to_exec_result_or_raise
Traceback (most recent call last):
File "/home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/engine/process.py", line 241, in fallible_to_exec_result_or_raise
raise ProcessExecutionFailure(
pants.engine.process.ProcessExecutionFailure: Process 'Building mypy.pex with 1 requirement: mypy==0.782' failed with exit code 1.
stdout:
stderr:
Failed to spawn a job for DistributionTarget(interpreter=PythonInterpreter('/usr/local/bin/python3.8', PythonIdentity('/usr/local/bin/python3.8', 'cp38', 'cp38', 'manylinux2014_x86_64', (3, 8, 5)))): [Errno 2] No such file or directory: '/home/toolchain/.pex/unzipped_pexes/49b4b32295a60a0a4dfc0659c3a44f93560c4a81/.deps/pex-2.1.16-py2.py3-none-any.whl/pex/__pycache__/variables.cpython-37.pyc.139923989690656'
Traceback (most recent call last):
File "/home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 256, in run
engine_result = self._run_v2()
File "/home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 168, in _run_v2
return self._maybe_run_v2_body(goals, poll=False)
File "/home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 185, in _maybe_run_v2_body
return self.graph_session.run_goal_rules(
File "/home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/init/engine_initializer.py", line 125, in run_goal_rules
exit_code = self.scheduler_session.run_goal_rule(
File "/home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/engine/internals/scheduler.py", line 568, in run_goal_rule
self._raise_on_error([t for _, t in throws])
File "/home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/engine/internals/scheduler.py", line 527, in _raise_on_error
raise ExecutionError(
pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered:
Engine traceback:
in select
in `typecheck` goal
in Typecheck using MyPy
in pants.backend.python.typecheck.mypy.rules.mypy_typecheck_partition
in pants.backend.python.util_rules.pex.create_pex
in pants.engine.process.fallible_to_exec_result_or_raise
Traceback (most recent call last):
File "/home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/engine/process.py", line 241, in fallible_to_exec_result_or_raise
raise ProcessExecutionFailure(
pants.engine.process.ProcessExecutionFailure: Process 'Building mypy.pex with 1 requirement: mypy==0.782' failed with exit code 1.
stdout:
stderr:
Failed to spawn a job for DistributionTarget(interpreter=PythonInterpreter('/usr/local/bin/python3.8', PythonIdentity('/usr/local/bin/python3.8', 'cp38', 'cp38', 'manylinux2014_x86_64', (3, 8, 5)))): [Errno 2] No such file or directory: '/home/toolchain/.pex/unzipped_pexes/49b4b32295a60a0a4dfc0659c3a44f93560c4a81/.deps/pex-2.1.16-py2.py3-none-any.whl/pex/__pycache__/variables.cpython-37.pyc.139923989690656'

# Fixed code
def cache_distribution(cls, zf, source, target_dir):
    # type: (ZipFile, str, str) -> Distribution
    """Possibly cache a wheel from within a zipfile into `target_dir`.

    Given a zipfile handle and a source path prefix corresponding to a wheel install embedded within
    that zip, maybe extract the wheel install into the target cache and then return a distribution
    from the cache.

    :param zf: An open zip file (a zipped pex).
    :param source: The path prefix of a wheel install embedded in the zip file.
    :param target_dir: The directory to cache the distribution in if not already cached.
    :returns: The cached distribution.
    """
    with atomic_directory(target_dir, source=source, exclusive=True) as target_dir_tmp:
        if target_dir_tmp is None:
            TRACER.log("Using cached {}".format(target_dir))
        else:
            with TRACER.timed(
                "Caching {}:{} in {}".format(zf.filename, source, target_dir)
            ):
                for name in zf.namelist():
                    if name.startswith(source) and not name.endswith("/"):
                        zf.extract(name, target_dir_tmp)

    dist = DistributionHelper.distribution_from_path(target_dir)
    assert dist is not None, "Failed to cache distribution: {} ".format(source)
    return dist