# Buggy code
def isolated():
    """Returns a chroot for third_party isolated from the ``sys.path``.

    PEX will typically be installed in site-packages flat alongside many other distributions; as such,
    adding the location of the pex distribution to the ``sys.path`` will typically expose many other
    distributions. An isolated chroot can be used as a ``sys.path`` entry to effect only the exposure
    of pex.

    :return: An isolation result.
    :rtype: :class:`IsolationResult`
    """
    global _ISOLATED
    if _ISOLATED is None:
        from pex import vendor
        from pex.common import atomic_directory
        from pex.util import CacheHelper
        from pex.variables import ENV
        from pex.third_party.pkg_resources import (
            resource_isdir,
            resource_listdir,
            resource_stream,
        )

        module = "pex"

        # TODO(John Sirois): Unify with `pex.util.DistributionHelper.access_zipped_assets`.
        def recursive_copy(srcdir, dstdir):
            os.mkdir(dstdir)
            for entry_name in resource_listdir(module, srcdir):
                if not entry_name:
                    # The `resource_listdir` function returns a '' entry name for the directory
                    # entry itself if it is either present on the filesystem or present as an
                    # explicit zip entry. Since we only care about files and subdirectories at this
                    # point, skip these entries.
                    continue
                # NB: Resource path components are always separated by /, on all systems.
                src_entry = "{}/{}".format(srcdir, entry_name) if srcdir else entry_name
                dst_entry = os.path.join(dstdir, entry_name)
                if resource_isdir(module, src_entry):
                    recursive_copy(src_entry, dst_entry)
                elif not entry_name.endswith(".pyc"):
                    with open(dst_entry, "wb") as fp:
                        with closing(resource_stream(module, src_entry)) as resource:
                            shutil.copyfileobj(resource, fp)

        pex_path = os.path.join(vendor.VendorSpec.ROOT, "pex")
        with _tracer().timed("Hashing pex"):
            dir_hash = CacheHelper.dir_hash(pex_path)
        isolated_dir = os.path.join(ENV.PEX_ROOT, "isolated", dir_hash)

        with _tracer().timed("Isolating pex"):
            with atomic_directory(isolated_dir) as chroot:
                if chroot:
                    with _tracer().timed("Extracting pex to {}".format(isolated_dir)):
                        recursive_copy("", os.path.join(chroot, "pex"))

        _ISOLATED = IsolationResult(pex_hash=dir_hash, chroot_path=isolated_dir)
    return _ISOLATED


# 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 isolated():
    """Returns a chroot for third_party isolated from the ``sys.path``.

    PEX will typically be installed in site-packages flat alongside many other distributions; as such,
    adding the location of the pex distribution to the ``sys.path`` will typically expose many other
    distributions. An isolated chroot can be used as a ``sys.path`` entry to effect only the exposure
    of pex.

    :return: An isolation result.
    :rtype: :class:`IsolationResult`
    """
    global _ISOLATED
    if _ISOLATED is None:
        from pex import vendor
        from pex.common import atomic_directory
        from pex.util import CacheHelper
        from pex.variables import ENV
        from pex.third_party.pkg_resources import (
            resource_isdir,
            resource_listdir,
            resource_stream,
        )

        module = "pex"

        # TODO(John Sirois): Unify with `pex.util.DistributionHelper.access_zipped_assets`.
        def recursive_copy(srcdir, dstdir):
            os.mkdir(dstdir)
            for entry_name in resource_listdir(module, srcdir):
                if not entry_name:
                    # The `resource_listdir` function returns a '' entry name for the directory
                    # entry itself if it is either present on the filesystem or present as an
                    # explicit zip entry. Since we only care about files and subdirectories at this
                    # point, skip these entries.
                    continue
                # NB: Resource path components are always separated by /, on all systems.
                src_entry = "{}/{}".format(srcdir, entry_name) if srcdir else entry_name
                dst_entry = os.path.join(dstdir, entry_name)
                if resource_isdir(module, src_entry):
                    recursive_copy(src_entry, dst_entry)
                elif not entry_name.endswith(".pyc"):
                    with open(dst_entry, "wb") as fp:
                        with closing(resource_stream(module, src_entry)) as resource:
                            shutil.copyfileobj(resource, fp)

        pex_path = os.path.join(vendor.VendorSpec.ROOT, "pex")
        with _tracer().timed("Hashing pex"):
            dir_hash = CacheHelper.dir_hash(pex_path)
        isolated_dir = os.path.join(ENV.PEX_ROOT, "isolated", dir_hash)

        with _tracer().timed("Isolating pex"):
            with atomic_directory(isolated_dir, exclusive=True) as chroot:
                if chroot:
                    with _tracer().timed("Extracting pex to {}".format(isolated_dir)):
                        recursive_copy("", os.path.join(chroot, "pex"))

        _ISOLATED = IsolationResult(pex_hash=dir_hash, chroot_path=isolated_dir)
    return _ISOLATED