Skip to content

import_importlib leaks module attr sets #157230

Description

@kddnewton

Bug report

Bug description:

Our CI (https://github.com/facebookincubator/cinder/actions/runs/29382592631/job/87249270535) was failing on test_pickle and test_pickletool with:

PicklingError: Can't pickle
<class 'importlib._bootstrap.BuiltinImporter'>:
it's not the same object as
importlib._bootstrap.BuiltinImporter

I believe this is happening because we run multiple test modules in the same interpreter, so the following sequence happens:

  • test_importlib.util.import_importlib() imports a source copy of importlib while blocking _frozen_importlib. During this import, importlib._bootstrap._setup() initializes import metadata on existing built-in modules. If builtins.__loader__ or builtins.__spec__ was originally absent, the source copy installs its own BuiltinImporter.
  • Although import_fresh_module() restores sys.modules, it does not restore attributes mutated on existing module objects. Consequently, builtins.__loader__ continues to reference the temporary source BuiltinImporter, while importlib._bootstrap.BuiltinImporter resolves to the restored frozen class.
  • Pickle serializes classes by module and qualified name and verifies that the resolved global is the same object. The two BuiltinImporter class objects therefore cause the identity check to fail.

To fix this we need to snapshot __loader__ and __spec__ before importing importlib and then restore them to their original values after.

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Linked PRs

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    testsTests in the Lib/test dirtopic-importlibtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions